【问题标题】:How to extract contents of a table from webpage using Python?如何使用 Python 从网页中提取表格的内容?
【发布时间】:2020-11-22 16:56:22
【问题描述】:

我在从网页中提取 kmz 和 zip 文件时需要帮助。以下代码能够提取表格,但不能提取表格内的文件和链接。我可以在我的代码中包含什么,以便输出表还包含链接和文件,而不仅仅是纯文本?

网页:

https://www.nhc.noaa.gov/gis/

代码:

import pandas as pd
url = 'https://www.nhc.noaa.gov/gis/'
result = pd.read_html(url)[0]
result

【问题讨论】:

  • 您要下载文件吗?
  • 是的,我想下载这些文件。
  • 输出应该是一个表格,我可以使用它下载这些文件。意思是,实际网页表上的链接也应该在输出表上工作。

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


【解决方案1】:

我会说使用 beautifulsoup (bs4) 而不是 pandas 来解析 html。

pip install beautifulsoup4 requests

然后就这么简单

import bs4
import requests

result = bs4.BeautifulSoup(requests.get('https://www.nhc.noaa.gov/gis/').content, features='html.parser')
for link in result.find('table').find_all('a'):
    print(link.attrs['href'])

【讨论】:

  • 我不知道为什么,但似乎 beautifulsoup 不适用于此网页。此外,我需要表格形式的输出。
【解决方案2】:

你可以使用beautifulsoup获取所有链接。

from bs4 import BeautifulSoup
import requests
import pandas as pd
url = 'https://www.nhc.noaa.gov/gis/'

res = requests.get(url)
soup = BeautifulSoup(res.text, "html.parser")
table = soup.find("table")
for anchor in table.find_all("a"):
    print("Text - {}, Link - {}".format(anchor.get_text(strip=True), anchor["href"]))

输出:

Text - Irma Example, Link - /gis/examples/al112017_5day_020.zip
Text - Cone, Link - /gis/examples/AL112017_020adv_CONE.kmz
Text - Track, Link - /gis/examples/AL112017_020adv_TRACK.kmz
Text - Warnings, Link - /gis/examples/AL112017_020adv_WW.kmz
Text - shp, Link - forecast/archive/al092020_5day_latest.zip
Text - Cone, Link - /storm_graphics/api/AL092020_CONE_latest.kmz
Text - Track, Link - /storm_graphics/api/AL092020_TRACK_latest.kmz
Text - Warnings, Link - /storm_graphics/api/AL092020_WW_latest.kmz

如果您想保留数据帧,请不要再次通过read_html 进行网络调用。重用响应对象。

df = pd.read_html(res.text)

要获取完整链接,请将以下内容附加到所有链接。

https://www.nhc.noaa.gov

代码:

for anchor in table.find_all("a"):
    print("Text - {}, Link - {}".format(anchor.get_text(strip=True), prefix + anchor["href"]))

输出:

Text - Irma Example, Link - https://www.nhc.noaa.gov/gis/examples/al112017_5day_020.zip
Text - Cone, Link - https://www.nhc.noaa.gov/gis/examples/AL112017_020adv_CONE.kmz
Text - Track, Link - https://www.nhc.noaa.gov/gis/examples/AL112017_020adv_TRACK.kmz
Text - Warnings, Link - https://www.nhc.noaa.gov/gis/examples/AL112017_020adv_WW.kmz
Text - shp, Link - https://www.nhc.noaa.govforecast/archive/al092020_5day_latest.zip
Text - Cone, Link - https://www.nhc.noaa.gov/storm_graphics/api/AL092020_CONE_latest.kmz
Text - Track, Link - https://www.nhc.noaa.gov/storm_graphics/api/AL092020_TRACK_latest.kmz
Text - Warnings, Link - https://www.nhc.noaa.gov/storm_graphics/api/AL092020_WW_latest.kmz

要下载文件,请再次使用requests 并下载文件

【讨论】:

  • bs4 不适用于我们的桌子。如您所见,您的代码提供了 8 个文件作为输出。但是,表中有超过 8 个文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-17
  • 1970-01-01
  • 2013-02-16
  • 2012-04-21
相关资源
最近更新 更多