我们使用联盟链接。它们让我们能够维持运营,而您无需承担任何费用。

如何使用 Beautifulsoup 抓取表格

有关如何使用 Beautifulsoup 抓取表格的分步指南。

重要提示:本教程将使用一个真实案例,因此您需要安装requestsBeautifulsoup库。

步骤 1.首先,让我们导入 Beautifulsoup 库。

				
					from bs4 import BeautifulSoup
				
			

步骤 2.然后,导入 requests 库。

				
					import requests
				
			

步骤三:获取目标着陆页的源代码。本例中我们将使用雅虎网站。

雅虎页面
				
					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).

注意:如果同一页面上有多个不同的表格,则可以通过类来指定要抓取的表格。

表有一个 W(100%) 类

步骤 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属性来获取特定的列值,因为它们存在,但这并非总是如此,所以请坚持使用通用方法。

“如何使用 Beautifulsoup 抓取表格”中步骤 8 的示例

步骤 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)
				
			
“如何使用 Beautifulsoup 抓取表格”中步骤 10 的示例

您得到的是列表的列表,每个列表包含 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)