如何使用BeautifulSoup从Oddshark.com解析此javascript?

时间:2018-11-10 14:22:30

标签: python web-scraping beautifulsoup

正在研究一个小的网络抓取程序,以获取一些数据并帮助我下注。

最终,我想在这样的页面(https://www.oddsshark.com/nfl/arizona-kansas-city-odds-november-11-2018-971332)上分析本周各场比赛的“趋势”部分

我当前的算法:

  1. 获取https://www.oddsshark.com/nfl/scores
  2. 解析网页上的“ vs”小按钮,其中包含所有游戏的链接
  3. 解析趋势

这是我的开始方式:

from bs4 import BeautifulSoup
import requests

url = "https://www.oddsshark.com/nfl/scores"
result = requests.get("https://www.oddsshark.com/nfl/scores")
print ("Status: ", result.status_code)

content = result.content
soup = BeautifulSoup(content, 'html.parser')

print (soup)

当我查看输出时,实际上看不到任何链接。是否会导致很多javascript网站?

任何对代码/算法的指针表示赞赏!

3 个答案:

答案 0 :(得分:1)

您可以使用此站点使用的内部API获取所有链接并对其进行迭代以获取趋势信息,该信息嵌入在script标签中,并带有id:gc-data

import requests
import json
from bs4 import BeautifulSoup

r = requests.get(
    'https://io.oddsshark.com/ticker/nfl', 
    headers = {
        'referer': 'https://www.oddsshark.com/nfl/scores'
    }
)

links = [
    (
        t["event_date"], 
        t["away_name"], 
        t["home_name"], 
        "https://www.oddsshark.com{}".format(t["matchup_link"])
    )
    for t in r.json()['matchups']
    if t["type"] == "matchup"
]

for t in links:
    print("{} - {} vs {} => {}".format(t[0],t[1],t[2],t[3]))
    r = requests.get(t[3])
    soup = BeautifulSoup(r.content, "lxml")
    trends = [
        json.loads(v.text)
        for v in soup.findAll('script', {"type":"application/json", "id":"gc-data"})
    ]
    print(trends[0]["oddsshark_gamecenter"]["trends"])
    print("#########################################")

答案 1 :(得分:0)

之所以看不到这些链接,是因为它们不在requests收到的响应中。这很可能是由于以下两个原因之一:

  1. 服务器识别出您正在尝试使用脚本抓取网站,并向您发送其他内容。通常这是由于User-Agent设置了requests
  2. 通过运行在浏览器中的JavaScript动态添加内容。

您可能会在Python脚本中使用无头浏览器来呈现此内容,最终得到的内容与您使用Chrome等浏览该网站时看到的内容相同。对于(1),可能还需要在请求中尝试使用User-Agent标头。

答案 2 :(得分:0)

数据通过javascript加载到趋势表,但实际上包含在您收到的html内的script标签中。您可以这样解析:

import requests
import json
from bs4 import BeautifulSoup

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0'
}

response = requests.get('https://www.oddsshark.com/nfl/arizona-kansas-city-odds-november-11-2018-971332', headers=headers)

soup = BeautifulSoup(response.text, "lxml")

data = json.loads(soup.find("script", {'id': 'gc-data'}).text)
print(data['oddsshark_gamecenter']['trends'])

输出:

  

{'local':{'title':'Trends'},'away':[{'value':'Arizona is 4-1-1   过去6场比赛的ATS'},{'value':'亚利桑那在过去8场比赛中获得2-6 SU   游戏'},{'value':“在亚利桑那州的最后8个比赛中,总比赛次数已减少   12个游戏“},{'value':'亚利桑那州在最近11场比赛中是3-7-1 ATS   {'value':'亚利桑那州在最近6场比赛中是2-4苏   路'} ...