当然,这是可能的。然而,看到这个特定页面的 DOM 是如何使用 JavaScript 异步填充的,BeautifulSoup 将无法看到您尝试抓取的数据。通常,这是大多数人建议您使用 Selenium 或 PlayWright 等无头浏览器/网络驱动程序来模拟浏览会话的地方 - 但您很幸运。对于这个特定页面,您不需要无头浏览器或 Scrapestorm 或 BeautifulSoup - 您只需要第三方 requests 模块。当您访问此页面时,它恰好向提供 JSON 的 REST API 发出 HTTP GET 请求。 JSON 响应包含表中的所有信息。如果您记录浏览器的网络流量,您可以看到对 API 的请求:
这是响应 JSON 的样子 - 字典列表:
从中,您可以复制 API URL 和相关的查询字符串参数来制定您自己对该 API 的请求:
def main():
import requests
url = "https://api.pantheon.world/person_ranks"
params = {
"select": "name,l,l_,age,non_en_page_views,coefficient_of_variation,hpi,hpi_prev,id,slug,gender,birthyear,deathyear,bplace_country(id,country,continent,slug),bplace_geonameid(id,place,country,slug,lat,lon),dplace_country(id,country,slug),dplace_geonameid(id,place,country,slug),occupation_id:occupation,occupation(id,occupation,occupation_slug,industry,domain),rank,rank_prev,rank_delta",
"birthyear": "gte.-3501",
"birthyear": "lte.2020",
"hpi": "gte.0",
"order": "hpi.desc.nullslast",
"limit": "50",
"offset": "0"
}
response = requests.get(url, params=params)
response.raise_for_status()
for person in response.json():
print(f"{person['name']} was a {person['occupation']['occupation']}")
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
输出:
Muhammad was a RELIGIOUS FIGURE
Genghis Khan was a MILITARY PERSONNEL
Leonardo da Vinci was a INVENTOR
Isaac Newton was a PHYSICIST
Ludwig van Beethoven was a COMPOSER
Alexander the Great was a MILITARY PERSONNEL
Aristotle was a PHILOSOPHER
...
从这里将这些信息写入 CSV 或 excel 文件很简单。您可以使用params 查询字符串参数字典中的"limit": "50" 和"offset": "0" 键值对来检索不同人的信息。
编辑 - 要获取每个人的缩略图,您需要构建以下形式的 URL:
https://pantheon.world/images/profile/people/{PERSON_ID}.jpg
其中{PERSON_ID} 是与给定人员的id 键关联的值:
...
for person in response.json():
image_url = f"https://pantheon.world/images/profile/people/{person['id']}.jpg"
print(f"{person['name']}'s image URL: {image_url}")
如果您将 openpyxl 用于您的 excel 文件,这里有一个 useful answer,它向您展示了如何在给定图像 URL 的单元格中插入图像。但是,我建议您使用 requests 而不是 urllib3 来向图像发出请求。