如何使用 Beautifulsoup 从 DIV 获取文本
有关如何使用 Beautifulsoup 提取 div 标签内容的分步指南。
重要提示:我们将在本教程中使用真实示例,因此您需要 要求 以及 美汤 已安装库。
步骤 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的代码如下:
div_text=soup.find("div",{"class":"intro__small-text"}).get_text()
步骤 6。 让我们通过打印来检查我们的代码是否有效。
print(div_text)
结果:
恭喜,您已使用 Beautifulsoup 找到并提取了 id 的内容。以下是完整脚本:
from bs4 import BeautifulSoup
import requests
r=requests.get("https://proxyway.com/")
soup=BeautifulSoup(r.content,"html.parser")
div_text=soup.find("div",{"class":"intro__small-text"}).get_text()
print(div_text)