【问题标题】:Scrapping Tables on a Web page with BeautifulSoap使用 BeautifulSoup 在网页上抓取表格
【发布时间】:2022-01-04 23:56:43
【问题描述】:

我需要在 Python 中使用美洲 500 强公司的信息做一个 DataFrame:

https://www.americaeconomia.com/negocios-industrias/estas-son-las-500-mayores-empresas-de-america-latina-2021

我尝试进行网络报废,当我打印(tabla)时,它显示 [] 或 None...

from bs4 import BeautifulSoup
import requests

url = 'https://www.americaeconomia.com/negocios-industrias/estas-son-las-500-mayores-empresas-de-america-latina-2021'
page = requests.get(url)

soup = BeautifulSoup(page.text, 'html.parser')

tabla = soup.find('table', {"id":"awesomeTable"})
print(tabla)

【问题讨论】:

    标签: python web web-scraping html-table


    【解决方案1】:

    会发生什么?

    总是先看看你的汤——这就是事实。内容总是与开发工具中的视图略有不同。

    你不会在你的汤中找到桌子,因为它在 iframe 中。

    如何解决?

    使用 iframe 源的 url 来执行您的请求:

    https://rk.americaeconomia.com/display/embed/500-latam/2021
    

    示例

    import requests
    from bs4 import BeautifulSoup
    headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'}
    r = requests.get('https://rk.americaeconomia.com/display/embed/500-latam/2021',headers=headers)
    soup = BeautifulSoup(r.text,'lxml')
    data = []
    for row in soup.select('#awesomeTable tbody tr.dataRow'):
        data.append(list(row.stripped_strings))
    
    pd.DataFrame(data, columns=list(soup.select_one('#awesomeTable tr').stripped_strings))
    

    输出

    RK 2021 EMPRESA PAÍS
    1 PETROBRAS BRA
    2 JBS BRA
    3 AMÉRICA MÓVIL MX
    4 PEMEX MX
    5 VALE BRA
    ... ... ...

    【讨论】:

    • 谢谢!!!!是否可以提取每个公司内部的数据?
    • 如果你点击,还有另一个表格,里面有很多信息。
    • 嗨刺猬!谢谢您的帮助!我一天都不能再做Q了……但是你能帮我解决这个问题吗?
    猜你喜欢
    • 2022-10-17
    • 1970-01-01
    • 2020-10-25
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多