Selenium为数组(列表)中的每个项创建多个chrome线程,并同时执行函数

2024-06-16 12:20:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为列表中的每个项目创建多个chrome线程,并同时为列表中的每个项目执行该函数,但不知道从何处开始任何帮助都将不胜感激。你知道吗

代码片段

import sys

def spotify(elem1, elem2, elem3):

    print("proxy: {}, cc: {}, cvc: {}".format(elem1, elem2, elem3))


def get_cc():
    cc = ['5136154545452522', '51365445452823', '51361265424522']
    return cc

def get_cvc():
    cvc = ['734', '690', '734']
    return cvc

def get_proxies():
    proxies = ['51.77.545.171:8080', '51.77.254.171:8080', '51.77.258.82:8080']
    return proxies

proxArr = get_proxies()
ccArr = get_cc()
cvcArr = get_cvc()
yeslist = ['y','yes']

for elem in zip(proxArr, ccArr, cvcArr):
    spotify(elem[0], elem[1], elem[2])
    restart=input("Do you wish to start again: ").lower()
    if restart not in yeslist:
        sys.exit("Exiting")

Tags: 项目列表getreturndefsysspotifycc
1条回答
网友
1楼 · 发布于 2024-06-16 12:20:23

与答案here类似,您可以启动多个Chrome线程。你知道吗

  • 定义一个执行Selenium代码的函数,在本例中为execute_chrome
  • 将所有必需的参数添加到函数定义中
  • Thread调用中将参数作为元组传递,例如args=(elem, )
  • 使用与另一个Python包不同的名称保存脚本,例如my_selenium_tests.py
  • 最好从命令行运行脚本,而不是从交互式环境(例如Jupyter笔记本)

    from selenium import webdriver
    import threading
    import random
    import time
    
    number_of_threads = 4
    
    def execute_chrome(url):
        chrome = webdriver.Chrome()
        chrome.get(url)
        time.sleep(1 + random.random() * 5)
        driver.quit()
    
    urls = ('https://www.google.com', 
            'https://www.bing.com', 
            'https://www.duckduckgo.com', 
            'https://www.yahoo.com')
    
    threads = []
    for i in range(number_of_threads):
        t = threading.Thread(target=execute_chrome, args=(urls[i], ))
        t.start()
        threads.append(t)
    
    for thread in threads:
        thread.join()
    

相关问题 更多 >