【问题标题】:How to use re() to extract data from javascript variable using scrapy?如何使用 re() 从使用 scrapy 的 javascript 变量中提取数据?
【发布时间】:2015-08-14 22:45:28
【问题描述】:

我的 items.py 文件是这样的:

from scrapy.item import Item, Field

class SpiItem(Item):
    title = Field()
    lat = Field()
    lng = Field()
    add = Field()

蜘蛛是:

import scrapy
import re

from spi.items import SpiItem

class HdfcSpider(scrapy.Spider):
    name = "hdfc"
    allowed_domains = ["hdfc.com"]
    start_urls = ["http://hdfc.com/branch-locator"]

    def parse(self,response):
        addresses = response.xpath('//script')
        for sel in addresses:
            item = SpiItem()
            item['title'] = sel.xpath('//script[@type="text/javascript"][1]').re('(?<="title":).+(?=")')
            item['lat'] = sel.xpath('//script[@type="text/javascript"][1]').re('(?<="latitude":).+(?=")')
            item['lng'] = sel.xpath('//script[@type="text/javascript"][1]').re('(?<="longitude":).+(?=")')
            item['add'] = sel.xpath('//script[@type="text/javascript"][1]').re('(?<="html":).+(?=")')
            yield item

整个javascript代码,查看页面源代码,写在里面://html/body/table/tbody/tr[348]/td[2]

为什么我的代码不起作用? 我只想提取 items 文件中提到的四个字段。

【问题讨论】:

标签: javascript python regex web-scraping scrapy


【解决方案1】:

不要使用正则表达式逐字段提取,而是提取完整的locations 对象,通过json.loads() 加载它,然后从您将获得的 Python 字典中提取所需的数据:

def parse(self,response):
    pattern = re.compile(r"var locations= ({.*?});", re.MULTILINE | re.DOTALL)
    locations = response.xpath('//script[contains(., "var locations")]/text()').re(pattern)[0]
    locations = json.loads(locations)
    for title, data in locations.iteritems():
        print title

【讨论】:

  • @Aditya 首先,你不需要循环遍历脚本——你只需要找到一个script。另外,您基本上是在您找到的每个script 标签内搜索script 标签,从逻辑上讲,这不会导致任何内容被刮掉。
  • @Aditya 无论如何,我提供了一种更好、更可靠的方法。
猜你喜欢
  • 1970-01-01
  • 2022-10-12
  • 1970-01-01
  • 1970-01-01
  • 2015-12-11
  • 1970-01-01
  • 2013-06-26
  • 2016-07-05
  • 2018-05-23
相关资源
最近更新 更多