【问题标题】:Parsing Javascript In Python在 Python 中解析 Javascript
【发布时间】:2017-05-02 16:38:48
【问题描述】:

我通常使用 Beautiful Soup 来解析我需要的 html,但我遇到了一些我想从 here 获取的 Javascript。

 <script>
function Model(){
    this.players = [{".....data......:""}];...etc

我试着像...一样加载它

import json
scrape_url = "https://swishanalytics.com/optimus/nba/daily-fantasy-projections?date=2016-12-15"

result = json.loads(scrape_url)

但我得到“无法解码 Json”。不知道该怎么做。

【问题讨论】:

  • 正如你的标签所说,你知道你应该使用BeautifulSoup,但是为什么你的代码使用json.loads(URL)?请检查json 文档,它并没有按照你的想法做
  • 所以您想从脚本中提取数据?您首先需要隔离它 I.E.只获取字符串{".....data......:"},然后将其与json.loads一起使用
  • @MoinuddinQuadri,我无法使用 bs4
  • @TadhgMcDonald-Jensen 知道了,谢谢!
  • @TadhgMcDonald-Jensen 如何指定该数据区域?

标签: python python-2.7 beautifulsoup


【解决方案1】:

您可以使用jsonfinder 库从任意文本中提取 JSON:

from jsonfinder import jsonfinder
import requests

scrape_url = "https://swishanalytics.com/optimus/nba/daily-fantasy-projections?date=2016-12-15"
content = requests.get(scrape_url).text
for _, __, obj in jsonfinder(content, json_only=True):
    if (obj and
            isinstance(obj, list) and
            isinstance(obj[0], dict) and
            {'player_id', 'event_id', 'name'}.issubset(obj[0])
            ):
        break
else:
    raise ValueError('data not found')

# Now you can use obj
print(len(obj))
print(obj[0])

【讨论】:

  • 工作得很好:)
猜你喜欢
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-21
  • 2010-09-28
  • 2018-03-22
相关资源
最近更新 更多