以下是使用BeautifulSoup库查找具有不同扩展名的图像的代码示例:
from bs4 import BeautifulSoup
import requests
# 发送请求获取页面内容
url = "https://example.com" # 替换为要抓取图片的网页URL
response = requests.get(url)
html_content = response.text
# 使用BeautifulSoup解析页面内容
soup = BeautifulSoup(html_content, "html.parser")
# 查找所有的图像标签
img_tags = soup.find_all("img")
# 遍历图像标签并获取图像链接及扩展名
for img in img_tags:
img_url = img["src"]
img_extension = img_url.split(".")[-1]
# 判断扩展名是否为指定的类型
if img_extension in ["jpg", "jpeg", "png", "gif"]:
print(img_url)
上述代码中,首先我们使用requests
库发送请求并获取页面内容,然后使用BeautifulSoup库解析页面内容。接下来,使用find_all
方法查找所有的图像标签,并遍历这些标签。通过img["src"]
获取图像链接,并使用split
方法获取链接的扩展名。最后,通过判断扩展名是否为指定的类型(这里指定了jpg、jpeg、png和gif),打印出符合条件的图像链接。
请注意,代码中的url
变量需要替换为你要抓取图片的网页URL。另外,还可以根据需要调整所需的图像扩展名类型。