【问题标题】:Scrapy to extract data from javascript scriptScrapy 从 javascript 脚本中提取数据
【发布时间】:2018-05-23 08:52:29
【问题描述】:

我正在尝试从 espn 网站提取游戏赔率。 “moneyLine”赔率隐藏在一个脚本中,我只是无法弄清楚如何访问。理想情况下,每场比赛我都会排成一行。我已经设法逐行提取团队名称和分数,我希望有机会使用它。

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

这是输出

[<Selector xpath="//script[contains(., 'moneyLine')]/text()" data='\n\t\t\tvar espn = espn || {};\n\n\t\t\t// Build '>]

这是来自 Firefox 检查器窗口的示例,我可以看到“moneyLine”项目,只是无法隔离它们

【问题讨论】:

  • 它可以将所有脚本作为一个字符串提供给您,您必须使用标准字符串函数或正则表达式来处理它。如果你得到的字符串是正确的 JSON 字符串,那么你可以使用模块 json 将其转换为 python 字典。
  • 页面可以使用javascript从另一个url读取数据(主要是JSON数据)。如果你在 Firefox 中使用 DevTool 找到这个 url,那么你可以用 scrapy 阅读它。
  • 'page' 是一种方法吗?你指的是什么“另一个网址”?
  • page 表示 web page / portal - 您必须使用 DevTool 来检查所有 XHR 请求 - 如果其中一个请求发回您的数据,那么您就有 another url

标签: javascript python xpath scrapy web-crawler


【解决方案1】:

您的数据在 &lt;script&gt; 之间,在 data:queue: 之间,采用 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']

【讨论】:

  • 谢谢!这让我大部分时间都在那里。显然,我有一些关于 xpath 和 json 的学习......只需要找到时间
猜你喜欢
  • 2021-01-09
  • 2020-02-19
  • 2016-11-23
  • 2019-07-27
  • 1970-01-01
  • 2019-01-13
  • 1970-01-01
  • 1970-01-01
  • 2016-03-11
相关资源
最近更新 更多