我正在刮一个网站,它的脚本标签包含以下代码:
<script type="text/javascript">
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('set', 'content_group1', 'World');
gtag('set', 'content_group2', 'AFP');
gtag('config', 'UA-40396753-1', {
'custom_map': {"dimension6":"Id","dimension1":"Category","dimension3":"Author","dimension5":"PublishedDate"}
});
gtag('event', 'custom', {"Id":"news\/1696246","Category":"World","Categories":"World","Author":"AFP-119","Authors":"AFP","PublishedDate":"2022-06-23 07:08:42"});
</script>我需要刮掉值"PublishedDate":"2022-06-23 07:08:42" -这是我尝试过的:
time = response.xpath('//script[@type="text/javascript"]/text()').re(r"gtag\('event', 'custom', ({.*})\);")
json_data = json.loads(time, strict=False)
print('dawn time::', json_data['PublishedDate'])但是,我没有得到任何结果
发布于 2022-06-27 17:18:58
我解决这个问题的方法很简单:
time = response.xpath('//meta[@property="article:published_time"]/@content')[0].extract()因为我所需要的字段有一个相关的元标记。
发布于 2022-06-26 10:59:10
使用regex从选择器中获取数据,并使用json.loads()。
import scrapy
import json
class ExampleSpider(scrapy.Spider):
name = "example"
start_urls = ['file:///PathToFile/temp.html']
def parse(self, response):
all_data = response.xpath('//script[@type="text/javascript"]/text()').re(r"gtag\('event', 'custom', ({.*})\);")
for data in all_data:
data = json.loads(data)
yield {'PublishedDate': data['PublishedDate']}输出:
[scrapy.core.scraper] DEBUG: Scraped from <200 file:///PathToFile/temp.html>
{'PublishedDate': '2022-06-23 07:08:42'}https://stackoverflow.com/questions/72759756
复制相似问题