簡體   English   中英

Selenium Threads:如何使用代理(python)運行多線程瀏覽器

[英]Selenium Threads: how to run multi-threaded browser with proxy ( python)

我正在編寫一個腳本來使用多線程代理訪問網站,但現在我卡在多線程中,當我運行下面的腳本時,它打開了 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()

(祝大家新年快樂,萬事如意)

(我個人認為存在一個問題,當您啟動程序時,它會轉到新線程,該線程將從頭開始遍歷文本文件,因為您不會刪除它們)

當我和你現在做同樣的事情時,我也遇到了同樣的問題。 我知道您更希望獲得有關您的代碼的幫助,但我急於對其進行測試並希望為您提供幫助 ;),所以這里有一個對我有用的代碼......甚至還有一個 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()

希望能幫助到你 :)

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()

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 值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM