【问题标题】:Using scrapy to get data within a script使用scrapy在脚本中获取数据
【发布时间】:2016-06-03 17:39:13
【问题描述】:

我正在使用 scrapy 在以下脚本中获取给定 ID 的 field10 和 field12 的整数值:

<script>

    Autoslave.jQuery(function ($) {
        "use strict";
        var map = initMap([

        {"field1": "operational",
        "field2": "operational",
        "field3": "operational",
        "ID": 2,
        "field4": "some text",
        "field5": 48.8732135,
        "field6": 2.3903853,
        "field7": 1,
        "field8": "SPACE",
        "field9": "some text",
        "field10": 4,
        "field10": false,
        "field12": 0}, 

        {"field1": "operational",
        "field2": "operational",
        "field3": "operational",
        "ID": 3,
        "field4": "some text",
        "field5": 48.8592806,
        "field6": 2.3773563,
        "field7": 0,
        "field8": "SPACE",
        "field9": "some text",
        "field10": 2,
        "field11": false,
        "field12": 3},

...

</script>

在scrapy shell中,我已经成功地使用response.xpath('//script[14]/text()').extract()获取脚本文本,但是我不知道如何在文本中选择我的值,以获得定义的ID。任何想法如何做到这一点(也许使用正则表达式?)

【问题讨论】:

  • 你知道我的正则表达式模式是什么吗?谢谢!
  • 我不确定您要提取什么。您的 xpath 究竟返回了什么?您希望它看起来如何?
  • 我当前的 xpath 返回上面的文本。对于给定的ID,比如说2,我想获取链接的"field10" 和/或"field12" 值,在这种情况下分别是40

标签: python regex web-scraping scrapy


【解决方案1】:

此解决方案不使用正则表达式,但由于脚本中包含 json,我将使用 python 的 json 模块来获取必填字段。我会假设除了var map 之外没有任何其他变量。

script =  ''.join(response.xpath('//script[14]/text()').extract())
json_data = script.split("initMap(")[1].replace("</script>","")[:-1]
data = json.loads('{"data":'+json_data+'}')
fields = data["data"]
for f in fields:
    id = f["ID"]
    field10 = f["field10"]
    field12 = f["field12"]

【讨论】:

  • 谢谢!我认为使用 JSON 是一个很好的解决方案。但是我收到以下错误:TypeError:replace() 至少需要 2 个参数(给定 1 个)?
  • 谢谢,我设法获得了 JSON 数据!但是data = json.loads({"data":json_data}) 这条线返回给我:TypeError: expected string or buffer
  • 已更新。这是因为 json.loads 将字符串或缓冲区作为参数,而我们传递了 dict 。现在试试。它应该可以工作。
猜你喜欢
  • 2020-02-19
  • 2018-05-23
  • 1970-01-01
  • 2021-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多