硒与scrapy动态页面

Z. *_*Lin 74 python selenium scrapy web-scraping selenium-webdriver

我正在尝试使用scrapy从网页上抓取产品信息.我的待删节网页如下所示:

  • 从包含10个产品的product_list页面开始
  • 点击"下一步"按钮加载下10个产品(两个页面之间的网址不变)
  • 我使用LinkExtractor跟踪每个产品链接到产品页面,并获得我需要的所有信息

我试图复制next-button-ajax-call但是无法正常工作,所以我试试了selenium.我可以在一个单独的脚本中运行selenium的webdriver,但我不知道如何与scrapy集成.我应该把硒部分放在我的scrapy蜘蛛里?

我的蜘蛛非常标准,如下所示:

class ProductSpider(CrawlSpider):
    name = "product_spider"
    allowed_domains = ['example.com']
    start_urls = ['http://example.com/shanghai']
    rules = [
        Rule(SgmlLinkExtractor(restrict_xpaths='//div[@id="productList"]//dl[@class="t2"]//dt'), callback='parse_product'),
        ]

    def parse_product(self, response):
        self.log("parsing product %s" %response.url, level=INFO)
        hxs = HtmlXPathSelector(response)
        # actual data follows
Run Code Online (Sandbox Code Playgroud)

任何想法都表示赞赏.谢谢!

ale*_*cxe 104

这实际上取决于您如何刮取网站以及您希望获得的数据和数据.

这是一个如何使用Scrapy+ 在ebay上跟踪分页的示例Selenium:

import scrapy
from selenium import webdriver

class ProductSpider(scrapy.Spider):
    name = "product_spider"
    allowed_domains = ['ebay.com']
    start_urls = ['http://www.ebay.com/sch/i.html?_odkw=books&_osacat=0&_trksid=p2045573.m570.l1313.TR0.TRC0.Xpython&_nkw=python&_sacat=0&_from=R40']

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

    def parse(self, response):
        self.driver.get(response.url)

        while True:
            next = self.driver.find_element_by_xpath('//td[@class="pagn-next"]/a')

            try:
                next.click()

                # get the data and write it to scrapy items
            except:
                break

        self.driver.close()
Run Code Online (Sandbox Code Playgroud)

以下是"硒蜘蛛"的一些例子:


还有一种具有使用替代的SeleniumScrapy.在某些情况下,使用ScrapyJS中间件足以处理页面的动态部分.实际使用示例:

  • @alecxe是的,而我得到的概念.我仍然对使用selenium提取页面源的部分感到困惑,并将要剪切的元素传递给scrapy.例如.有一个加载更多按钮点击它将显示更多项目,但你提取这些项目的xpath.现在你如何将这些xpath传递给scrapy?因为只有你第一次请求页面时显示的项目才会被抓斗解析,而不是点击加载更多按钮后的硒 (4认同)
  • 有没有办法重新使用已被scrapy抓取的响应而不是使用`self.driver.get(response.url)`? (2认同)
  • @HalcyonAbrahamRamirez这只是scrapy蜘蛛中硒部分的一个例子.完成selenium之后,通常将`self.driver.page_source`传递给Scrapy的Selector实例以解析HTML,形成项实例,将它们传递给管道等.或者,可以解析selenium cookie并将其传递给Scrapy提出其他要求.但是,如果你不需要scrapy框架架构的强大功能,那么,当然,你可以只使用selenium - 它本身在定位元素方面非常强大. (2认同)
  • @HalcyonAbrahamRamirez得到它,我会加载更多的项目,直到没有更多的东西添加.然后,取`driver.page_source`并将其传递给`Selector()`.. (2认同)