网页抓取 masslottery.com 使用美丽的汤

时间:2021-06-17 19:45:56

标签: python html beautifulsoup nested

我正在尝试使用美丽的汤来获得所有出现过的基诺号码。我主要知道如何做到这一点,但我遇到了一个问题。我需要获得比赛号码和每场比赛的号码。然而,使用美丽的汤,我不知道如何访问这些。我将包括 html 的屏幕截图,以及我尝试过的屏幕截图,以及我正在检查的页面的链接。 html code

我正在尝试访问 <div class="winning-number-ball-circle solid">,正如您在该图片中看到的那样,但所有 html 都是嵌套的。 我试过了 soup.find_all('div',{'class':'winning-number-ball-circle solid'}) 这不起作用。有谁知道如何访问内部元素?

这是我的代码:


from bs4 import BeautifulSoup
import urllib.request

mass = 'https://www.masslottery.com/tools/past-results/keno?draw_date=2021-06-17'
page = urllib.request.urlopen(mass)
soup = BeautifulSoup(page,'lxml')

div = soup.find('div',{'class','winning-number-ball-circle solid'})
print(div)


提前致谢!

2 个答案:

答案 0 :(得分:1)

数据来自浏览器通过运行 Javascript 进行的 REST API 调用。您需要对此提出请求,然后使用返回的 json

import requests

r = requests.get('https://www.masslottery.com/rest/keno/getDrawsByDateRange?startDate=2021-06-17&endDate=2021-06-17').json()

感谢@MendelG 建议使用 Pandas 进行格式化:

import requests
import pandas as pd

r = requests.get('https://www.masslottery.com/rest/keno/getDrawsByDateRange?startDate=2021-06-17&endDate=2021-06-17').json()
pd.json_normalize(r['draws'])

答案 1 :(得分:0)

divs = soup.findAll('div',{'class':['winning-number-ball-circle','solid']})
for div in divs:
    print(div.text)

使用soup.findAll,您可以找到所有类名为“获胜号码球圈”和“实心”的div 这将返回一个列表。 用一个为你显示这些div的文字