Skip to main content
 首页 » 编程设计

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

2024年10月17日7lovecherry

我使用了 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()