使用Scrapy获取JavaScript函数的参数

Ari*_*zBi 7 javascript python regex scrapy web-scraping

我想知道是否可以使用类似于此代码的代码从Scrapy中提取JavaScript函数的参数:

<script type="text/javascript">
    var map;
  function initialize() {
    var fenway = new google.maps.LatLng(43.2640611,2.9388228);
  };
}
</script>
Run Code Online (Sandbox Code Playgroud)

我想提取坐标43.26406112.9388228.

ale*_*cxe 11

这是re()方法有用的地方.

我们的想法是找到script通过标签xpath()和使用re()提取latlngscript标签中的内容.演示来自scrapy shell:

$ scrapy shell index.html
>>> response.xpath('//script').re(r'new google\.maps\.LatLng\(([0-9.]+),([0-9.]+)\);')
[u'43.2640611', u'2.9388228']
Run Code Online (Sandbox Code Playgroud)

其中index.html包括:

<script type="text/javascript">
    var map;
  function initialize() {
    var fenway = new google.maps.LatLng(43.2640611,2.9388228);
  };
}
</script>
Run Code Online (Sandbox Code Playgroud)

当然,在你的情况下,xpath不仅仅是//script.

FYI,new google\.maps\.LatLng\(([0-9.]+),([0-9.]+)\);正则表达式使用保存组 ([0-9.]+)来提取坐标值.

另请参阅使用具有正则表达式的选择器.