本指南将教你如何使用Beautifulsoup逐步抓取表格数据。
重要提示:我们将在本教程中使用现实生活中的示例,因此您需要安装requests和Beautifulsoup库。
步骤 1. 首先导入 Beautifulsoup 库。
from bs4 import BeautifulSoup
步骤2. 然后,导入requests库。
import requests
步骤 3.获取目标登陆页面的源代码。在此示例中我们将使用雅虎。
r=requests.get("https://finance.yahoo.com/cryptocurrencies/")
通用代码如下所示:
r=requests.get("Your URL")
步骤 4. 将 HTML 代码转换为名为soup的 Beautifulsoup 对象 。
soup=BeautifulSoup(r.content,"html.parser")
步骤5.然后,检查页面源。看到表中有一个类W(100%parser)
。
注意:如果同一页面上有多个不同的表,则类可以指定抓取的表。步骤6.使用BeautifulSoup解析页面内容,找到HTML内容中的表格并将整个表格元素分配给table_element变量。
soup = BeautifulSoup(r.content, "html.parser") table_element = soup.find("table", class_="W(100%)")
注意:目标是从目标表中抓取所有行。
步骤 7.初始化一个新的列表变量来保存数据。
output_list = []
步骤8.搜索表中的所有tr标签以获取之前保存的table_element中的所有行。您还将获得标题行和所有变量。
table_rows = table_element.find_all("tr")
注意:在这种情况下,还可以通过引用aria-label属性来获取特定的列值,因为它们存在,但情况并非总是如此,因此请坚持使用通用方法。
步骤 9. 以下 for 循环将迭代从表中获取的所有行,并获取每行的所有子行。每个子元素都是表中的一个td元素。获取子项后,迭代row_children列表并将每个元素的文本值附加到row_data列表中以保持简单。
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格式输出并将结果写入输出文件。另外,转换为Pandas DataFrame并使用数据进行一些分析。
结果:
恭喜,您已经学会了如何使用 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)