gpt4 book ai didi

python - Selenium 为未使用的蜘蛛运行 Firefox 驱动程序

转载 作者:太空宇宙 更新时间:2023-11-04 03:00:25 27 4
gpt4 key购买 nike

我使用了 Selenium 的 Firefox 驱动程序在我的 Scrapy 中的一些蜘蛛中加载和废弃网页项目。

问题:
Selenium 在运行所有蜘蛛时运行一个 Firefox 实例,即使那些我没有导入 webdriver 也没有调用 webdriver.Firefox() 的蜘蛛。

预期行为:
Selenium 运行一个 Firfox 的实例 当我运行已经在 webdriver.Firefox() 中使用的蜘蛛时。

为什么这很重要?
蜘蛛完成后我将退出 Firefox 实例,但很明显这不会发生在不使用 Selenium 的蜘蛛中。

没有使用 Selenium 的蜘蛛
这个蜘蛛没有使用 Selenium,我希望它不会运行 Firefox。

class MySpider(scrapy.Spider):
name = "MySpider"
domain = 'www.example.com'
allowed_domains = ['http://example.com']
start_urls = ['http://example.com']

def parse(self, response):
for sel in response.css('.main-content'):
# Article is a scrapy.item
item = Article()
item['title'] = sel.css('h1::text').extract()[0]
item['body'] = sel.css('p::text').extract()[0]
yield item

最佳答案

问题实际上在于我如何在旨在使用 Selenium 的蜘蛛中实例化 webdriver.Firefox 模块:

class MySpider(scrapy.Spider):
# basic scrapy setting
driver = webdriver.Firefox()

def parse(self, response):
self.driver.get(response.url)
result = scrapy.Selector(text=self.driver.page_source)
# scrap and yield items to pipeline
# then in certain condition:
self.driver.quit()

为什么会这样?
当运行 Scrapy 命令时,python 解释项目中的所有类。因此,无论我尝试运行哪个蜘蛛,Selenium 都会为包含此命令行的每个蜘蛛类运行一个新的 webdriver.Firefox 实例。

解决方案
刚刚将 webdriver 实例化移动到类 init 方法:

def __init__(self):
self.driver = webdriver.Firefox()

关于python - Selenium 为未使用的蜘蛛运行 Firefox 驱动程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41080960/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com