【问题标题】:Webscraping output []网页抓取输出 []
【发布时间】:2021-08-26 16:12:04
【问题描述】:
嘿,我只是想测试 Python Webscraping,但我不知道为什么这不起作用。
作为输出,我变成了 [],仅此而已。
有人有想法吗?因为如果我去网站搜索我找到的元素。
from bs4 import BeautifulSoup
import requests
html_text = requests.get("https://osu.ppy.sh/users/20488254").text
soup = BeautifulSoup(html_text, "lxml")
job = soup.find("div", class_ = "profile-detail__col profile-detail__col--bottom-right")
print(job)
【问题讨论】:
标签:
python
web-scraping
beautifulsoup
【解决方案1】:
玩家信息是通过 JS 动态加载的。因此,您不能使用纯 bs4 抓取动态内容。幸运的是,他们在 script 标签内提供了 json 格式的用户信息。如果您打开页面源代码并查找json-user,您会看到有一个标签:
<script id="json-user" type="application/json">
{"avatar_url":"https:\/\/a.ppy.sh\/20488254?1622470835.jpeg","country_code":"AT","default_group":"default","id":20488254,...
</script>
您可以在该标签中获取 json 并获取有关玩家的任何信息。下面是它的样子:
import json
import requests
from bs4 import BeautifulSoup
html_text = requests.get("https://osu.ppy.sh/users/20488254").text
soup = BeautifulSoup(html_text, "lxml")
json_data = json.loads(soup.find('script', {'id':'json-user'}).string)
现在假设您正在寻找玩家的全球排名。您需要做的就是找到正确的键来导航:
player_rank = json_data['statistics']['global_rank']
# -> 199303