【问题标题】:How to scraper `JS` dependent content using `Scrapy`如何使用`Scrapy`刮取`JS`依赖的内容
【发布时间】:2016-04-08 02:17:23
【问题描述】:

我正在使用Scrapywebsite (proptiger.com) 中抓取HTML 内容。但是当我搜索任何元素作为响应时,它没有找到任何元素。

页面上有文字2, 3 BHKXPath//div[@class="spec-value f16"]可以访问。但是当我使用response.xpath('//div[@class="spec-value f16"]')时,它并没有返回上面的文字。

https://wiki.python.org/moin/BeginnersGuide 等普通网站上运行良好,但在 99acres.comproptiger.com

等网站上运行良好

任何帮助都会有所帮助。

【问题讨论】:

  • 文档中没有具有itemprop 属性的元素。
  • 如果内容是由 JavaScript 生成的,那么你就找不到了。

标签: python web-scraping scrapy web-crawler scrapy-spider


【解决方案1】:

使用scrapy shell,您正在搜索的itemprop xpath 不可用,正如@furas 所说,某些内容是由JavaScript 生成的。您可以通过将 Selenium 添加到 scrapy 来获取此内容。 Selenium 获取一个 URL,使用 Web 浏览器呈现它,scrapy 可以正常访问生成的 HTML。下面的代码是让您开始使用 Firefox 的框架,但它也适用于其他浏览器。我也建议使用 Firebug for Firefox,它对练习 xpath 很有用。

import scrapy
from scrapy import signals
from scrapy.xlib.pydispatch import dispatcher
from scrapy.http import TextResponse

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

class SearchSpider(scrapy.Spider):
    name = "search"

    allowed_domains = ['www.somedomain.com']
    start_urls = ['https://www.somewebsite.com']

    def __init__(self, filename=None):
        # wire us up to selenium
        self.driver = webdriver.Firefox()
        dispatcher.connect(self.spider_closed, signals.spider_closed)

    def spider_closed(self, spider):
        self.driver.close()

    def parse(self, response):
        item = someItem()

        # Load the current page into Selenium
        self.driver.get(response.url)

        try:
            WebDriverWait(self.driver, 30).until(EC.presence_of_element_located((By.XPATH, '//span[@itemprop="name"]')))
        except TimeoutException:
            item['status'] = 'timed out'

        # Sync scrapy and selenium so they agree on the page we're looking at then let scrapy take over
        resp = TextResponse(url=self.driver.current_url, body=self.driver.page_source, encoding='utf-8')
        # scrape as normal

【讨论】:

    【解决方案2】:

    本教程将引导您完成以下任务:

    • 创建一个新的 Scrapy 项目
    • 编写蜘蛛来抓取网站并提取数据
    • 使用命令行导出抓取的数据
    • 将蜘蛛更改为递归跟踪链接
    • 使用蜘蛛参数

    Scrapy 是用 Python 编写的。如果您是该语言的新手,您可能希望先了解该语言是什么样的,以充分利用 Scrapy。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      相关资源
      最近更新 更多