Python 使用scrapy在脚本中获取数据

Python 使用scrapy在脚本中获取数据,python,regex,web-scraping,scrapy,Python,Regex,Web Scraping,Scrapy,我使用scrapy获取以下脚本中给定ID的字段10和字段12的整数值: <script> Autoslave.jQuery(function ($) { "use strict"; var map = initMap([ {"field1": "operational", "field2": "operational", "field3": "operational", "ID

我使用scrapy获取以下脚本中给定ID的字段10和字段12的整数值:

<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>

jQuery(函数($){
“严格使用”;
var-map=initMap([
{“字段1”:“操作”,
“现场2”:“操作”,
“字段3”:“操作”,
“ID”:2,
“字段4”:“一些文本”,
“字段5”:48.8732135,
“字段6”:2.3903853,
“字段7”:1,
“字段8”:“空间”,
“字段9”:“一些文本”,
“字段10”:4,
“字段10”:错误,
“field12”:0},
{“字段1”:“操作”,
“现场2”:“操作”,
“字段3”:“操作”,
“ID”:3,
“字段4”:“一些文本”,
“字段5”:48.8592806,
“字段6”:2.3773563,
“字段7”:0,
“字段8”:“空间”,
“字段9”:“一些文本”,
“字段10”:2,
“字段11”:错误,
“字段12”:3},
...

在scrapy shell中,我成功地使用
response.xpath('//script[14]/text()').extract()获得了脚本文本,但是我不知道如何在文本中为定义的ID选择值。有没有办法(可能使用regex?)

此解决方案不使用正则表达式,但由于脚本中包含
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"]
script=''.join(response.xpath('//script[14]/text()).extract())
json_data=script.split(“initMap”()[1]。替换(“,”)[:-1]
data=json.load(“{”data:“+json_data+'}”)
字段=数据[“数据”]
对于字段中的f:
id=f[“id”]
字段10=f[“字段10”]
field12=f[“field12”]

试试这个,你知道在我的例子中正则表达式模式是什么吗?谢谢!我不确定你想提取什么。你的xpath返回的确切内容是什么?你希望它看起来怎么样?我当前的xpath返回上面的文本。对于给定的
ID
,让我们假设
2
在这里,我想得到链接的
字段10
和/或
“field12”
值,在这种情况下是
4
0
,谢谢!我认为使用JSON是一个很好的解决方案。但是我得到了以下错误:TypeError:replace()至少需要2个参数(给定1个)?谢谢,我成功地获得了JSON数据!但是行
data=JSON.loads({“data”:JSON data})
返回我:
TypeError:expected string或buffer
更新了它。发生这种情况是因为
json。loads
将string或buffer作为参数,并且我们正在传递一个
dict
。请立即尝试。它应该可以工作。