使用Scrapy Xpath从脚本标签中获取数据并将其用作CSV



我一直在尝试使用Scrapy(xpath(从脚本标签中提取数据。我的主要问题是识别正确的div 和脚本标签。我是使用 xpath 的新手,非常感谢任何形式的帮助!

<script>    
var COUNTRY_SHOP_STATUS = "buy";
var COUNTRY_SHOP_URL = "";
try {
digitalData.page.pathIndicator.depth_2 = "mobile";
digitalData.page.pathIndicator.depth_3 = "mobile";
digitalData.page.pathIndicator.depth_4 = "smartphones";
digitalData.page.pathIndicator.depth_5 = "galaxy-s8";    
digitalData.product.pvi_type_name = "Mobile";
digitalData.product.pvi_subtype_name = "Smartphone";
digitalData.product.model_name = "SM-G950F";
digitalData.product.category = digitalData.page.pathIndicator.depth_3;
} catch(e) {}
</script>

我终于想用 model.name 和深度 3、4 和 5 的数据填充我的 csv 文件。我已经尝试了与此类似的问题中的其他解决方案,但它们似乎不起作用......

您可以使用regex提取所需的值:

import re
source = response.xpath("//script[contains(., 'COUNTRY_SHOP_STATUS')]/text()").extract()[0]
def get_values(parameter, script):
return re.findall('%s = "(.*)"' % parameter, script)[0]
print(get_values("pathIndicator.depth_5", source))
print(get_values("pvi_subtype_name", source))
print(get_values("model_name", source))
...

最新更新