【问题标题】:How to scrape hidden nested table tag with BeautifulSoup and Python?如何使用 BeautifulSoup 和 Python 抓取隐藏的嵌套表标签?
【发布时间】:2021-12-31 16:48:24
【问题描述】:

我一直在尝试从这个网站上找到这张桌子:https://consultas.anvisa.gov.br/#/medicamentos/25351532892201972/

我在下面使用这个方法:

from bs4 import BeautifulSoup
import requests

url= "https://consultas.anvisa.gov.br/#/medicamentos/25351532892201972/"
page = requests.get(url, verify=False)

soup = BeautifulSoup(page.content, 'html.parser')
print(soup.prettify())

for table in soup.find_all('table'):
    print(table)
    for subtable in table.find_all('table'):
        print(subtable)

没有任何结果,因为不知何故表格似乎被隐藏了。我可以使用 firefox 检查器(下图)查看标签和表格,但 BeautifulSoup 无法使用我迄今为止尝试的方法找到它。

我该怎么做才能找到这些隐藏的嵌套表?我已经尝试了很多方法通过soup.find(), soup.find_all(), soup.body.div.table.find_all() 找到它,但还没有成功。

提前谢谢你们! =)

【问题讨论】:

  • 总是先看看你的汤——这就是真相。内容总是与开发工具中的视图略有不同。内容是动态提供的,所以你应该用 selenium 试试。
  • https://consultas.anvisa.gov.br/api/consulta/medicamento/produtos/25351532892201972

标签: python web-scraping beautifulsoup


【解决方案1】:

您要查找的数据是通过 API 调用加载的(可以通过开发工具获取);调用返回一个json,所以不需要beautifulsoup:

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0',
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'en-US,en;q=0.5',
    'Accept-Encoding': 'gzip, deflate, br',
    'Referer': 'https://consultas.anvisa.gov.br/',
    'If-Modified-Since': 'Mon, 26 Jul 1997 05:00:00 GMT',
    'Cache-Control': 'no-cache',
    'Pragma': 'no-cache',
    'Authorization': 'Guest',
    'Connection': 'keep-alive',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
}

page = requests.get('https://consultas.anvisa.gov.br/api/consulta/medicamento/produtos/25351532892201972', headers=headers, verify=False)

data = json.loads(page.text)
data

这就是表格中信息的来源。

【讨论】:

  • 也注意到了这个调用,但不确定如何验证末尾的数字 (produtos/25351532892201972) 是否始终相同或如何从 html 中自动获取。你明白了吗?
  • 我打算用多页抓取。这个数字大约是一种产品。感谢您的回复。
  • @eduardosteps 不客气!
猜你喜欢
  • 2019-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-19
  • 1970-01-01
  • 2016-04-05
  • 2019-04-10
  • 2014-05-11
相关资源
最近更新 更多