【问题标题】:Selenium Threads: how to run multi-threaded browser with proxy ( python)Selenium Threads:如何使用代理运行多线程浏览器(python)
【发布时间】:2018-12-30 10:01:05
【问题描述】:

我正在编写一个脚本来使用具有多个线程的代理访问网站,但现在我被困在多个线程中,当我运行下面的脚本时,它会打开 5 个浏览器,但所有 5 个都使用 1 个代理,我想要 5 个浏览器使用不同的代理,有人可以帮我完成吗?谢谢你

这是我的脚本:

from selenium import webdriver
from selenium import webdriver
import time , random
import threading


def e():

    a = open("sock2.txt", "r")
    for line in a.readlines():

        b = line
        prox = b.split(":")
        IP = prox[0]
        PORT = int(prox[1].strip("\n"))
        print(IP)
        print(PORT)


        profile = webdriver.FirefoxProfile()
        profile.set_preference("network.proxy.type", 1)
        profile.set_preference("network.proxy.socks", IP)
        profile.set_preference("network.proxy.socks_port", PORT)
        try:

            driver = webdriver.Firefox(firefox_profile=profile)
            driver.get("http://www.whatsmyip.org/")
        except:
            print("Proxy Connection Error")
            driver.quit()
        else:
            time.sleep(random.randint(40, 70))
            driver.quit()
for i in range(5):
    t = threading.Thread(target=e)
    t.start()

(祝大家新年快乐,万事如意)

【问题讨论】:

  • sock2.txt 的内容是什么?您是否配置了 5 个不同的代理,并且每行输入都有不同的 IP 和 PORT 值?
  • 是的!它是txt文件中的袜子列表
  • 每行输入的代理IP和PORT是否有不同的值?
  • 是的,每一行都有不同的值和端口

标签: python multithreading selenium webdriver


【解决方案1】:

Dominik Lašo 正确捕获了它 - 每个线程从头开始处理文件。它可能应该是这样的:

from selenium import webdriver
from selenium import webdriver
import time , random
import threading


def e(ip, port):
    profile = webdriver.FirefoxProfile()
    profile.set_preference("network.proxy.type", 1)
    profile.set_preference("network.proxy.socks", IP)
    profile.set_preference("network.proxy.socks_port", PORT)
    try:
        driver = webdriver.Firefox(firefox_profile=profile)
        driver.get("http://www.whatsmyip.org/")
    except:
        print("Proxy Connection Error")
        driver.quit()
    else:
        time.sleep(random.randint(40, 70))
        driver.quit()

my_threads = []
with open("sock2.txt", "r") as fd:
    for line in fd.readlines():
        line = line.strip()
        if not line:
           continue
        prox = line.split(":")
        ip = prox[0]
        port = int(prox[1])
        print('-> {}:{}'.format(ip, port))
        t = threading.Thread(target=e, args=(ip, port,))
        t.start()
        my_threads.append(t)

for t in my_threads:
    t.join()

【讨论】:

  • 我编辑IP,PORT--->它工作!但它运行了很多线程,我将 50 个袜子放在 txt 文件中,它运行 50 个浏览器!有没有办法只运行 5 个线程然后运行接下来的 5 个线程?
  • 您可以阅读该文件并创建一个包含 5 个 IP 和端口的列表。然后在一个 while 循环中,处理列表中的 5 个元素(5 个线程)。一旦这 5 个结束,处理下一个 5,依此类推。更有效的实现是使用 concurrent.futures 中的 ThreadPoolExecutor,池大小为 5 - 它会自动将最大线程一次限制为 5。
  • 谢谢,沙拉德!如果你有一点时间,你能帮我用 ThreadPoolExecutor 编辑上面的脚本吗?
【解决方案2】:

(我个人认为一个问题是当你启动一个程序时,它会转到新线程,它会从头开始遍历文本文件,因为你没有删除它们)

当我和你现在做同样的事情时,我遇到了同样的问题。我知道你更愿意在你的代码方面需要帮助,但我急于测试它并想帮助你;),所以这里有一个对我有用的代码......甚至还有一个 chrome 的任务杀手(你只是必须将其编辑到Firefox)

如果我是你,我会在打开文件后启动线程,因为看起来你每次启动时都从第一行打开同一个文件

links = [ // Link you want to go to ]

def funk(xxx , website):
    link = website
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--proxy-server=%s' % str(xxx))
    chromedriver = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'chromedriver')
    chrome = webdriver.Chrome(chromedriver, chrome_options=chrome_options)
    try :
        // Do stuff
    except:
        print('exception')
    chrome.close()

for link in links:
    f = open('proxies.txt')
    line = f.readline()
    x = 1
    xx = 0
    while line:
        if number_of_used_proxies < 10:
            print(line)
            line = f.readline()
            try:
                threading.Timer(40, funk, [line, link]).start()
            except Exception as e:
                print(e)
            time.sleep(1)
            x += 1
            number_of_used_proxies += 1
        else:
            time.sleep(100)
            for x in range(1, 10):
                try:
                    xzxzx = 'os.system("taskkill /f /im chrome.exe")'
                    os.system("killall 'Google Chrome'")
                except:
                    print("NoMore")
            time.sleep(10)
            number_of_used_proxies = 0

    f.close()

希望对你有帮助:)

【讨论】:

  • 我很想要,但我做不到
【解决方案3】:

vantuong:以下是使用 ThreadPoolExecutor 解决问题的方法。

参考https://docs.python.org/3/library/concurrent.futures.html

from selenium import webdriver
import time, random
#import threading
import concurrent.futures

MAX_WORKERS = 5

def get_proxys(data_file):
    proxys = []
    with open(data_file, "r") as fd:
        for line in fd.readlines():
            line = line.strip()
            if not line:
               continue
            prox = line.split(":")
            ip = prox[0]
            port = int(prox[1])
            proxys.append((ip, port))
    return proxys


def e(ip, port):
    profile = webdriver.FirefoxProfile()
    profile.set_preference("network.proxy.type", 1)
    profile.set_preference("network.proxy.socks", IP)
    profile.set_preference("network.proxy.socks_port", PORT)
    try:
        driver = webdriver.Firefox(firefox_profile=profile)
        driver.get("http://www.whatsmyip.org/")
    except:
        print("Proxy Connection Error")
        driver.quit()
    else:
        time.sleep(random.randint(40, 70))
        driver.quit()


with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
    proxys = get_proxys('sock2.txt')
    tasks = {executor.submit(e, proxy[0], proxy[1]): proxy for proxy in proxys}
    for task in concurrent.futures.as_completed(tasks):
        proxy = tasks[task]
        try:
            data = task.result()
        except Exception as exc:
            print('{} generated an exception: {}'.format(proxy, exc))
        else:
            print('{} completed successfully'.format(proxy))

有趣的练习:尝试使用不同的 MAX_WORKERS 值。

【讨论】:

    猜你喜欢
    • 2020-07-19
    • 1970-01-01
    • 2012-04-10
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 2017-09-23
    相关资源
    最近更新 更多