【问题标题】:Selenium runs Firefox driver for spiders not used inSelenium 为未使用的蜘蛛运行 Firefox 驱动程序
【发布时间】:2017-04-26 03:28:24
【问题描述】:

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

问题:
Selenium 在运行所有蜘蛛时运行一个 Firefox 实例,如果我没有导入 webdriver 并且没有调用 webdriver.Firefox()

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

为什么这很重要?
蜘蛛完成后,我将退出 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

【问题讨论】:

  • 请澄清您的具体问题或添加其他详细信息以准确突出您的需要。正如目前所写的那样,很难准确地说出你在问什么。请参阅How to Ask 页面以获得澄清此问题的帮助。
  • @JeffC 希望现在很清楚。谢谢
  • 这没有帮助。您的代码显示您在 MySpider 类中实例化 Firefox 浏览器。为什么你认为它不会运行?
  • @JeffC 我试图解释这就是我只在一些蜘蛛中使用 Selenium 的方式,这些蜘蛛会废弃动态页面,其余的蜘蛛不导入,因此不使用 selenium一点也不。但是当我运行它们时,正在打开一个 Firefox 实例
  • 然后将代码发布到您不使用 Firefox 的地方,这样我们就可以看到不工作的代码。向我们展示工作代码并不能真正帮助我们解决问题。

标签: python selenium scrapy


【解决方案1】:

问题实际上在于我如何在打算使用 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()

【讨论】:

    猜你喜欢
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多