我正试图从网站上抓取一张桌子,但效果不佳。我正在使用Python 3.7.4和bs4 4.8.2。另外,我不精通HTML,所以请谅解某些术语。
我正在尝试使用“ id ='track_1_box'”来刮擦父类下的表类,可以看到here。我试图提取的信息是字符串“ title ='Canada'”和“ Cole”,但现在我什至无法访问该表。
这是我到目前为止尝试过的。
import requests
import numpy as np
from bs4 import BeautifulSoup
from csv import writer
#%%
url = 'https://www.mkleaderboards.com/mkw/charts/world/nonsc/12'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find("table", class_='table')
但是,“ table”变量返回一个空列表。我也尝试过使用
访问父类soup.find_all(class_ = 'panel inline_box track_box')
返回
[<div class="panel inline_box track_box" id="track_1_box">
</div>, <div class="panel inline_box track_box" id="track_2_box">
</div>, <div class="panel inline_box track_box" id="track_3_box">
</div>, <div class="panel inline_box track_box" id="track_4_box">
</div>]
但不是四个div类的“内部”。
我做错什么了吗?或者网站上有什么阻止我刮擦桌子的东西?
答案 0 :(得分:0)
数据是通过JavaScript加载的,但是您可以使用requests
模块来获取数据:
import json
import requests
url = 'https://www.mkleaderboards.com/mkw/charts/world/nonsc/12'
api_url = 'https://www.mkleaderboards.com/api/charts/mkw_nonsc_world/{num}'
cup_id = int(url.split('/')[-1])
# box 1:
box1 = requests.get(api_url.format(num=cup_id*4+1)).json()
# box 2:
box2 = requests.get(api_url.format(num=cup_id*4+2)).json()
# box 3:
box3 = requests.get(api_url.format(num=cup_id*4+3)).json()
# box 4:
box4 = requests.get(api_url.format(num=cup_id*4+4)).json()
# uncomment this to print data to screen:
# print(json.dumps(box1, indent=4))
# print(json.dumps(box2, indent=4))
# print(json.dumps(box3, indent=4))
# print(json.dumps(box4, indent=4))
# print box1 to screen:
for d in box1['data']:
print('{:<30} {:<20} {}'.format(d['name'], d['country_name'], d['score_formatted']))
打印:
Cole Canada 1:08.774
Kasey United States 1:08.881
SwareJonge Netherlands 1:09.036
Sosis United States 1:09.050
Paul M. United States 1:09.066
Sword United Kingdom 1:09.118
Gustav Sweden 1:09.136
Guy United States 1:09.143
Glaceon Japan 1:09.157
Liam [MKW] United Kingdom 1:09.171