selinium如何多线程_Selenium+Python多线程

本文介绍了如何在Python中使用Selenium和threading库实现多线程爬虫。通过创建线程并调用test_baidu函数,分别在Chrome和Firefox浏览器上运行测试用例,访问百度并搜索关键词。最后,所有线程完成后再结束程序。
摘要由CSDN通过智能技术生成

Python通过两个标准库thread和threading提供对线程的支持。

我们应避免使用thread模块,原因是它不支持线程守护(即当主线程退出时,所有的子线程不管它们还在工作与否,都会被强行退出)。

from threading import Thread

from selenium import webdriver

from time import sleep, ctime

#测试用例

def test_baidu(host, browser):

print('start: %s' % ctime())

print(host, browser)

#当前运行环境

desired_capabilities = {'browserName': browser}

driver = webdriver.Remote(command_executor = host,

desired_capabilities = desired_capabilities)

driver.get('https://www.baidu.com')

driver.find_element_by_id('kw').send_keys(browser)

sleep(3)

driver.close()

if __name__ == '__main__':

#定义分布式运行环境

env = {'http://localhost:4444/wd/hub': 'chrome',

'http://localhost:5555/wd/hub': 'firefox'}#,

#'http://:6666/wd/hub': 'internet explorer'}

#定义空线程数组

threads = []

#获取线程数

loops = range(len(env))

#创建线程,并追加入线程数组

for host, browser in env.items():

thread = Thread(target=test_baidu, args=(host, browser))

threads.append(thread)

#启动线程

for i in loops:

threads[i].start()

#守护线程

for i in loops:

threads[i].join()

print('end: %s' % ctime)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值