如何使用 Beautifulsoup 从‘img’标签获取‘src’属性
有关如何使用 Beautifulsoup 查找图像源的分步指南。
大部分数据是在 2023 年 XNUMX 月和 XNUMX 月收集的。
步骤 1。 让我们首先导入 Beautifulsoup 库。
from bs4 import BeautifulSoup
步骤 2。 然后,导入请求库。
import requests
步骤 3。 获取目标登录页面的源代码。
r=requests.get("https://books.toscrape.com/")
步骤 4。 将 HTML 代码转换为名为的 Beautifulsoup 对象 汤.
soup=BeautifulSoup(r.content,"html.parser")
步骤 5。 检查页面以找到您想要提取的图像对象。
该图像对象的代码如下所示:
thumbnail_elements = soup.find_all("img", class_ = "thumbnail")
注意: 对于此网站,您可以通过以下方式查找图片 IMG 标签包含 缩略图 类。
步骤 6。 让我们通过打印来检查我们的代码是否有效。
print(thumbnail_elements)
步骤 7。 现在你需要得到 SRC 每个元素的属性。
for element in thumbnail_elements:
print (element['src'])
结果:
恭喜,您已使用 Beautifulsoup 找到并提取图像源的内容。以下是完整脚本:
from bs4 import BeautifulSoup
import requests
r = requests.get("https://books.toscrape.com/")
soup = BeautifulSoup(r.content, "html.parser")
thumbnail_elements = soup.find_all("img", class_ = "thumbnail")
print(thumbnail_elements)
for element in thumbnail_elements:
print (element['src'])
#for element in thumbnail_elements:
# print ("https://books.toscrape.com/" + element['src'])
如果你重建完整的 URL,你可以访问 图片.