selinium如何多线程_selenium实现并发

for循环和多线程 + selenium

实例一

for循环

# -*- coding: utf-8 -*-

"""

Datetime: 2019/6/22

Author: Zhang Yafei

Description:

"""

import time

from selenium import webdriver

from selenium.webdriver.chrome.options import Options

from concurrent.futures import ThreadPoolExecutor

import functools

chrome_options = Options()

chrome_options.add_argument("--headless")

chrome_options.add_argument('--disable-gpu')

def timeit(func):

"""

装饰器: 判断函数执行时间

:param func:

:return:

"""

@functools.wraps(func)

def inner(*args, **kwargs):

start = time.time()

ret = func(*args, **kwargs)

end = time.time() - start

if end < 60:

print(f'花费时间:\t{round(end, 2)}秒')

else:

min, sec = divmod(end, 60)

print(f'花费时间\t{round(min)}分\t{round(sec, 2)}秒')

return ret

return inner

class PolicyUrlDownload(object):

""" 政策数据下载 """

def __init__(self, url, pages_num, output_file, a_xpath, headless: bool=True):

self.url_list = [url.format(page) for page in range(1, pages_num+1)]

self.output_file = output_file

self.a_xpath = a_xpath

if headless:

self.driver = webdriver.Chrome(options=chrome_options)

else:

self.driver = webdriver.Chrome()

def start(self, page, url):

with open(self.output_file, mode='a', encoding='utf-8') as file:

print(f"make request to {url}")

self.driver.get(url)

titles = self.driver.find_elements_by_xpath(self.a_xpath)

for title in titles:

href = title.get_attribute('href')

file.write(f'{page}\t{href}\n')

print(f'{url} download completed')

def run(self):

for page, url in enumerate(self.url_list):

self.start(page+1, url)

self.driver.close()

@timeit

def main(setting):

policy_data = PolicyUrlDownload(**setting)

policy_data.run()

if __name__ == '__main__':

start_time = time.time()

print('######################## 开始下载 #########################')

# 多配置页面地址下载

settings = [

{

'output_file': '药品供应保障综合的管理.txt',

&

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Gerapy-Selenium 中开启并发请求,可以使用 Gerapy-Selenium 提供的 `SeleniumRequest` 的 `meta` 参数来传递并发请求的配置信息。下面是一个示例: ```python import asyncio from gerapy_selenium import SeleniumRequest class MySpider(scrapy.Spider): name = 'myspider' allowed_domains = ['example.com'] start_urls = ['http://example.com/page1', 'http://example.com/page2', 'http://example.com/page3'] custom_settings = { 'CONCURRENT_REQUESTS': 5, # 并发请求数量 'DOWNLOAD_DELAY': 0.5, # 请求间隔时间 } def start_requests(self): for url in self.start_urls: yield SeleniumRequest(url=url, callback=self.parse, meta={'driver_wait_timeout': 10}) async def parse(self, response): driver = response.meta['driver'] # 使用 driver.find_element 等方法进行元素定位和操作 title = driver.find_element(By.XPATH, '//h1').text yield {'title': title} ``` 在上述示例中,`CONCURRENT_REQUESTS` 设置了并发请求数量为 5,`DOWNLOAD_DELAY` 设置了请求间隔时间为 0.5 秒。通过在 `start_requests` 方法中使用 `SeleniumRequest` 并设置 `meta` 参数来传递额外的配置信息,例如 `driver_wait_timeout` 表示等待浏览器加载完成的超时时间。 注意,Gerapy-Selenium 提供了异步的支持,因此可以在 Spider 中使用异步代码。在上述示例中,使用了 `async` 和 `await` 关键字定义了异步的 `parse` 方法。 需要注意的是,并发请求数量的设置可能会受到浏览器驱动的限制,不同的浏览器驱动有不同的并发请求数量限制。此外,设置过大的并发请求数量可能会导致网站的反爬机制触发,请根据实际情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值