如何使用 Beautifulsoup 抓取表格
有关如何使用 Beautifulsoup 抓取表格的分步指南。
重要提示:我们将在本教程中使用真实示例,因此你需要 要求 以及 美汤 已安装库。
步骤 1。 让我们首先导入 Beautifulsoup 库。
from bs4 import BeautifulSoup
步骤 2。 然后,导入请求库。
import requests
步骤 3。 获取目标登录页面的源代码。本例中我们将使用 Yahoo。
r=requests.get("https://finance.yahoo.com/cryptocurrencies/")
普遍适用的代码如下所示:
r=requests.get("Your URL")
步骤 4。 将 HTML 代码转换为名为的 Beautifulsoup 对象 汤.
soup=BeautifulSoup(r.content,"html.parser")
步骤 5。 然后,检查页面源代码。看到表格有一个类 W(100%parser).
注意: 如果同一页面上有多个不同的表格,则类可以指定要抓取的表格。
步骤 6。 使用以下方式解析页面内容 美丽汤,在 HTML 内容中找到表格,并将整个表格元素分配给 表元素 变量。
soup = BeautifulSoup(r.content, "html.parser")
table_element = soup.find("table", class_="W(100%)")
注意: 目标是从目标表中抓取所有行。
步骤 7。 初始化一个新的列表变量来保存数据。
output_list = []
步骤 8。 搜索全部 tr 标签在表中获取所有行 表元素 这是之前保存的。您还将获得标题行和所有变量。
table_rows = table_element.find_all("tr")
注意: 在这种情况下,也可以通过引用获取特定列的值 咏叹调标签 属性,因为它们存在,但情况并非总是如此,因此请坚持通用方法。
步骤 9。 以下 for 循环将遍历从表中获得的所有行,并获取每行的所有子项。每个子项都是一个 td 表中的元素。获取子元素后,遍历 row_children 列出并将每个元素的文本值附加到 行数据 列表以使其保持简单。
for row in table_rows:
row_children = row.children
row_data = []
for child in row_children:
row_data.append(child.get_text())
output_list.append(row_data)
步骤 10。 让我们显示结果。
for row in output_list:
print (row)
您得到的是列表的列表,每个列表包含 12 个元素,这些元素与表格列相对应。第一行包含表格标题。
注意: 这使得格式化输出变得容易 CSV/JSON 并将结果写入输出文件。此外,要转换为 熊猫数据框 并利用数据进行一些分析。
结果:
恭喜,您已经学会了如何使用 Beautifulsoup 抓取表格数据。以下是完整脚本:
from bs4 import BeautifulSoup
import requests
r = requests.get("https://finance.yahoo.com/cryptocurrencies/")
soup = BeautifulSoup(r.content, "html.parser")
table_element = soup.find("table", class_="W(100%)")
output_list = []
table_rows = table_element.find_all("tr")
for row in table_rows:
row_children = row.children
row_data = []
for child in row_children:
row_data.append(child.get_text())
output_list.append(row_data)
for row in output_list:
print (row)