Selenium Threads:如何使用代理(python)运行多线程浏览器

van*_*ong 5 python selenium multithreading webdriver

我正在编写一个脚本来使用多线程代理访问网站,但现在我卡在多线程中,当我运行下面的脚本时,它打开了 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()
Run Code Online (Sandbox Code Playgroud)

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

Sha*_*rad 5

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

\n\n
from selenium import webdriver\nfrom selenium import webdriver\nimport time , random\nimport threading\n\n\ndef e(ip, port):\n    profile = webdriver.FirefoxProfile()\n    profile.set_preference("network.proxy.type", 1)\n    profile.set_preference("network.proxy.socks", IP)\n    profile.set_preference("network.proxy.socks_port", PORT)\n    try:\n        driver = webdriver.Firefox(firefox_profile=profile)\n        driver.get("http://www.whatsmyip.org/")\n    except:\n        print("Proxy Connection Error")\n        driver.quit()\n    else:\n        time.sleep(random.randint(40, 70))\n        driver.quit()\n\nmy_threads = []\nwith open("sock2.txt", "r") as fd:\n    for line in fd.readlines():\n        line = line.strip()\n        if not line:\n           continue\n        prox = line.split(":")\n        ip = prox[0]\n        port = int(prox[1])\n        print(\'-> {}:{}\'.format(ip, port))\n        t = threading.Thread(target=e, args=(ip, port,))\n        t.start()\n        my_threads.append(t)\n\nfor t in my_threads:\n    t.join()\n
Run Code Online (Sandbox Code Playgroud)\n