【发布时间】:2019-05-24 13:56:48
【问题描述】:
我很难提取数据 首先我需要提取帖子的标题和发布日期 这是网址。
在 view-source 内部有一个 json 格式的脚本,其中包含我需要的数据
像这样,我裁剪其他文本以最小化空间
<script>
window.__RELAY_STORE__ = {"public_at":"2019-05-22T11:02:43-
04:00","updated_at":"2019-05-22T15:25:20-
04:00","thumbnail_attribution":null,"body":null,"title":"Safety Concerns
Over Tesla's Autopilot from Consumer Reports as Wall Street Turns Bearish"
</script>
我只需要获取“public_at”和“title”
我尝试过的是这个,
data = response.xpath("//script[contains(., 'window.__RELAY_STORE__')]/text()")
#Locate the script
datatxt = data.extract_first()
#Extract the script
start = datatxt.find('client:') - 2
end = datatxt.find('window.__REDUX_STATE__')
# find start and end of data
json_string = datatxt[start:end]
但是当我加载它或将其转换为 python 字典时
data = json.loads(json_string)
我遇到了类似这样的错误
Extra data: line 1 column 27284 (char 27283)
知道如何获取这些数据吗?
【问题讨论】:
-
json 字符串不是有效的 json 数据。也许发布
print(json_string)的输出,看看有什么问题。 -
是的,这就是为什么我试图使它成为一个有效的 json 字符串,并且我得到了这个错误“Extra data: line 1 column 27284 (char 27283)”
-
看看这个字符串,你就会明白为什么它无效了。
标签: python web-scraping scrapy