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

如何使用 Beautifulsoup 通过 id 查找元素

有关如何使用 Beautifulsoup 通过 id 查找元素的分步指南。

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

步骤 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。 找到您想要提取内容的 ID。我们将使用此标签作为示例:

查找元素 ID

这个id的代码如下:

				
					element_by_id=soup.find("section",{"id":"awarded-list"})
				
			

步骤 6。 让我们通过打印来检查我们的代码是否有效。

				
					print(element_by_id)
				
			

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

				
					from bs4 import BeautifulSoup
import requests
r=requests.get("https://proxyway.com/")
soup=BeautifulSoup(r.content,"html.parser")
element_by_id=soup.find("section",{"id":"awarded-list"})
print(element_by_id)