如何在Python中抓取带有图像的表格并导出到Excel?

1 python beautifulsoup web-scraping

我正在尝试从URL中抓取表格

我可以使用 Scrapestorm 工具抓取表格数据。我是 python 新手,无法从此URL获取数据。

from bs4 import BeautifulSoup

page = requests.get('https://pantheon.world/explore/rankings?show=people&years=-3501,2020')
soup = BeautifulSoup(page.text)
Run Code Online (Sandbox Code Playgroud)

Excel 中所需的输出:

在此输入图像描述

是否可以从网页上抓取表格数据和图像?

use*_*432 5

当然,这是可能的。然而,鉴于此特定页面的 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())
Run Code Online (Sandbox Code Playgroud)

输出:

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
...
Run Code Online (Sandbox Code Playgroud)

从这里开始,将此信息写入 CSV 或 Excel 文件非常简单。您可以使用查询字符串参数字典中的"limit": "50""offset": "0"键值params对来检索不同人的信息。

编辑 - 要获取每个人的缩略图,您需要构建以下形式的 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}")
Run Code Online (Sandbox Code Playgroud)

如果您使用的是openpyxlExcel 文件,这里有一个有用的答案,它向您展示了如何将图像插入到给定图像 URL 的单元格中。不过,我建议您使用requests而不是 来urllib3向图像发出请求。