【问题标题】:Using Selenium + Scrapy使用 Selenium + Scrapy
【发布时间】:2017-05-25 02:20:33
【问题描述】:

我正在尝试将 scrapy 与 selenium 一起使用,以便能够与 javascript 交互,并且仍然拥有 scrapy 提供的强大抓取框架。我写了一个脚本,访问http://www.iens.nl,在搜索栏中输入“阿姆斯特丹”,然后成功点击搜索按钮。单击搜索按钮后,我希望 scrapy 从新呈现的页面中检索元素。不幸的是,scrapy 没有返回任何值。

这是我的代码的样子:

from selenium import webdriver
from scrapy.loader import ItemLoader
from scrapy import Request
from scrapy.crawler import CrawlerProcess
from properties import PropertiesItem
import scrapy


class BasicSpider(scrapy.Spider):
    name = "basic"
    allowed_domains = ["web"]
    # Start on a property page
    start_urls = ['http://www.iens.nl']

    def __init__(self):
        chrome_path = '/Users/username/Documents/chromedriver'
        self.driver = webdriver.Chrome(chrome_path)

    def parse(self, response):
        self.driver.get(response.url)
        text_box = self.driver.find_element_by_xpath('//*[@id="searchText"]')
        submit_button = self.driver.find_element_by_xpath('//*[@id="button_search"]')
        text_box.send_keys("Amsterdam")
        submit_button.click()

        l = ItemLoader(item=PropertiesItem(), response=response)
        l.add_xpath('description', '//*[@id="results"]/ul/li[1]/div[2]/h3/a/')

        return l.load_item()


process = CrawlerProcess()
process.crawl(BasicSpider)
process.start()

“properties”是另一个看起来像这样的脚本:

from scrapy.item import Item, Field

class PropertiesItem(Item):
    # Primary fields
    description = Field()

问:我如何成功地让scrapy在硒到达的页面上通过其xpath找到我称之为“描述”的元素并将其作为输出返回?

提前致谢!

【问题讨论】:

  • @eLRuLL 它确实到达了parse,否则 selenium 不会移动到下一页对吗?
  • 你可能想看看这个,了解将 Scrapy 与 Selenium 结合的其他方法:stackoverflow.com/a/36085533/1204332

标签: javascript python selenium scrapy


【解决方案1】:

您分配给 ItemLoaderresponse 对象是 scrapy 响应,而不是 Selenium 的。

我建议使用 selenium 返回的页面源创建一个新的Selector

from scrapy import Selector
...

selenium_response_text = driver.page_source

new_selector = Selector(text=selenium_response_text)
l = ItemLoader(item=PropertiesItem(), selector=new_selector)
...

这样add_xpath 将从该响应结构中获取信息,而不是从scrapy(您实际上并不需要)中获取信息。

【讨论】:

  • 就像我说的;我想用scrapy来刮数据,因为它的速度!我知道如何使用硒。 :)
  • @titusAdam 速度在 selenium 中并不是一个真正的东西。如果你想要速度,你要么需要完全放弃 selenium,要么用支持异步渲染的东西替换它。即Splash
  • @Granitosaurus 是否可以像本例中的 selenium 那样在带有飞溅的页面中移动?
  • @titusAdam 可以使用 scrapy 单独来完成,无需任何 javascript 渲染。
  • @titusAdam 我刚刚回答了你发布的问题:我如何成功地让 scrapy 在 selenium 到达的页面上通过其 xpath 找到我称之为“描述”的元素并将其作为输出返回?
猜你喜欢
  • 2023-04-03
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 2018-02-04
  • 2016-04-28
  • 1970-01-01
  • 2020-08-30
相关资源
最近更新 更多