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

如何使用 Beautifulsoup 按类别查找元素

有关如何使用 Beautifulsoup 按类别查找元素的分步指南。

重要提示:我们将在本教程中使用真实示例,因此您需要安装请求和 Beautifulsoup 库。

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

				
					from bs4 import BeautifulSoup
				
			

步骤 2。 然后,导入请求库。

				
					import requests
				
			

步骤 3。 获取目标着陆页的源代码。在此示例中,我们将在主页上查找指南标题。

				
					r=requests.get("https://proxyway.com/")
				
			

普遍适用的代码如下所示:

				
					r=requests.get("Your URL")
				
			

步骤 4。 将 HTML 代码转换为名为的 Beautifulsoup 对象 .

				
					soup=BeautifulSoup(r.content,"html.parser")
				
			

步骤 5。  检查页面以找到您想要提取的类。

如何使用 Beautifulsoup 按类别查找元素

该类的代码如下:

				
					elements_by_class = soup.find_all(class_ = "archive-list__title")
				
			

注意: 因为我们想要查找所有标题而不是一个,所以我们使用 soup.find_all() 而不是 soup.find()。

第四步。让我们通过将脚本的输出打印到终端窗口来检查脚本是否有效。

				
					print(elements_by_class)
				
			
打印(元素按类别)

注意: 如果只想显示标题,可以获取每个抓取元素的字符串属性。

				
					for element in elements_by_class: print (element.string)
				
			
对于 elements_by_class 中的元素:打印(element.string

结果:

恭喜,您已使用 Beautifulsoup 找到并提取了类的内容。以下是完整脚本:

				
					from bs4 import BeautifulSoup
import requests
r = requests.get("https://proxyway.com/")
soup = BeautifulSoup(r.content, "html.parser")
elements_by_class = soup.find_all(class_ = "archive-list__title")

print(elements_by_class)

for element in elements_by_class:
    print (element.string)