【问题标题】:How can I grab multiple information from a table on a website using beautifulsoup [duplicate]如何使用beautifulsoup从网站上的表格中获取多个信息[重复]
【发布时间】:2018-05-13 14:04:20
【问题描述】:

我正试图弄清楚如何从https://www.fda.gov/Safety/Recalls/ 网站提取我想要的多个信息

import requests
from bs4 import BeautifulSoup

res = requests.get("https://www.fda.gov/Safety/Recalls/")
soup = BeautifulSoup(res.text, "lxml")

for item in soup.select("table td"):
    if "Undeclared" in item.text:
        brand = item.find_parents()[0].select("td")[1].text
        reason = item.text
        print(brand,reason)

如何从 html 中获取brand_link?

【问题讨论】:

  • 我建议,在您说“召回”的地方,考虑您的意思是“召回行”还是“表格单元格”,并相应地进行编辑以澄清。尤其是最后一点,您说您的代码“提取所有具有 : 的召回”。那里也有漏字。 :-)

标签: python-3.x web-scraping beautifulsoup


【解决方案1】:

我想这就是您的预期输出:

import requests
from bs4 import BeautifulSoup

res = requests.get("https://www.fda.gov/Safety/Recalls/")
soup = BeautifulSoup(res.text, "lxml")

for item in soup.select("table td"):
    if "Undeclared" in item.text:
        brand = item.find_parents()[0].select("td")[1].text
        reason = item.text
        print(brand,reason)

部分输出:

N/A   Undeclared Milk
Colorado Nut Company and various other private labels   Undeclared milk
All Natural, Weis, generic   Undeclared milk
Dilettante Chocolates   Undeclared almonds
Hot Pockets   Undeclared egg, milk, soy, and wheat
Figiâs   Undeclared Milk
Germack   Undeclared Milk

如果您还想获取品牌名称的链接,您可以执行以下操作:

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

url = "https://www.fda.gov/Safety/Recalls/"
res = requests.get(url)
soup = BeautifulSoup(res.text, "lxml")

for item in soup.select("table td"):
    if "Undeclared" in item.text:
        brand = item.find_parents()[0].select("td")[1].text
        brand_link = urljoin(url,item.find_parents()[0].select("td")[1].select("a")[0]['href'])
        reason = item.text
        print("Brand: {}\nBrand_link: {}\nReason: {}\n".format(brand,brand_link,reason))

输出:

Brand: N/A  
Brand_link: https://www.fda.gov/Safety/Recalls/ucm587012.htm
Reason: Undeclared Milk

【讨论】:

  • 表格中所有想要的项目最终都存储在td标签中。当您创建条件语句以访问以Undeclared 开头的数据时,您可能会注意到它们位于第 4 个td 标记中。因此,当您想要获得品牌名称时,您需要返回到相关的td 标签。但是,tr 是每个 td 标记的父级。因此,当您找到您的第一个搜索 Undeclared 时,您需要返回它的父级 tr 并执行下一次搜索第二个 td 嵌入品牌名称的标签。希望有帮助。请务必将此标记为答案。
  • 太棒了!快速提问:品牌名称也是一个链接。如果我想获取该链接,该怎么做?
  • 试试这个brand_link = item.find_parents()[0].select("td")[1].select("a")[0]['href']
  • 所以当我这样做时,我会得到这样的结果:/Safety/Recalls/ucm586430.htm 有没有办法获得fda.gov/Safety/Recalls/ucm583556.htm的实际链接
  • 当然。只要我靠近我的电脑,我就会告诉你。我是用手机写的。
猜你喜欢
  • 1970-01-01
  • 2019-05-31
  • 1970-01-01
  • 2021-01-07
  • 1970-01-01
  • 1970-01-01
  • 2020-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多