链接图像的精确计数

2024-03-29 12:47:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试通过python查找带有链接的图像(扩展名.jpg、.png、jpeg)的数量。我可以使用任何库,比如beautifulsoup。但我该怎么做呢。 我使用以下代码:

from bs4 import BeautifulSoup
soup = BeautifulSoup(open('HTMLS%5C110k_Source.htm'), "html.parser")
img_links = len(soup.find_all('.jpg'))
print("Number of Images : ", img_links)

但都是徒劳的。在


Tags: 代码from图像importimg数量png链接
2条回答

如果您阅读docs,这与编写一个循环一样简单

import bs4
import requests

url = 'somefoobar.net'
page = requests.get(url).text
soup = bs4.BeautifulSoup(page, 'lxml')

images = soup.findAll('img')

# loop through all img elements found and store the urls with matching extensions
urls = list(x for x in images if x['src'].split('.')[-1] in file_types)

print(urls)
print(len(urls))

您可以尝试使用^{},如下所示:

from lxml import html
with open('HTMLS%5C110k_Source.htm', 'r') as f:
    source = html.fromstring(f.read())
    print(len(source.xpath('//img[contains(@src, ".jpg") or contains(@src, ".jpeg") or contains(@src, ".png")]')))

相关问题 更多 >