用Scrapy提取JavaScript脚本中的数据

2024-05-16 06:21:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个espn网站上提取游戏的几率。“金钱线”的可能性被埋没在一个脚本中,我只是不知道如何访问它。理想的情况下,每场比赛我都会有一排胜算。我已经成功地提取了球队的名字和得分,我希望赔率与之相匹配。在

scrapy shell
fetch('http://www.espn.com/nfl/schedule/_/week/1')
response.xpath("//script[contains(., 'moneyLine')]/text()")

这是输出

^{pr2}$

这是firefox inspector窗口中的一个示例,我可以看到“moneyLine”项,只是无法将它们隔离开来
enter image description here


Tags: 脚本游戏网站情况shell可能性名字金钱
1条回答
网友
1楼 · 发布于 2024-05-16 06:21:32

您的数据在<script>之间,在data:和{}之间,格式为JSON。在

您可以使用标准字符串函数(即find(),切片)来切断此部分。
然后可以使用模块json转换为python字典。
然后你只需要找到moneyLine在这本字典中的位置。在

scrapy shell 'http://www.espn.com/nfl/schedule/_/week/1'

# get `<script>` as text
items = response.xpath("//script[contains(., 'moneyLine')]/text()")
txt = items.extract_first()

# find start and end of data 
#(I found this manually checking txt)
start = txt.find('data:') + 6 # manually found how many add to get correct JSON string
end = txt.find('queue:') - 6  # manually found how many substract to get correct JSON string

json_string = txt[start:end]

# convert to python dictionary
import json
data = json.loads(json_string)

# example data 
#(I found this manually using `data.keys(), data['sports'][0].keys(), etc.)
data['sports'][0]['leagues'][0]['events'][0]['odds']['home']['moneyLine']

相关问题 更多 >