【问题标题】:Exacting count of link Images链接图像的确切数量
【发布时间】:2018-04-05 05:20:53
【问题描述】:

我正在尝试通过 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)

但一切都是徒劳的。

【问题讨论】:

    标签: python web-scraping beautifulsoup html-parsing


    【解决方案1】:

    您可以尝试使用lxml.html,如下:

    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")]')))
    

    【讨论】:

    • 能找到具体的jpg,png jpeg吗?
    • 欢迎。如果它解决了您的问题,您可以将此答案标记为“已接受”
    【解决方案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))
    

    【讨论】:

    • 但是我们没有为 url 传递任何本地路径。我们在哪里传递它?
    • 我认为请求库没有被导入。如何在 python 3.above 中安装它。我正在使用 Visual Studio 代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 2014-05-07
    • 2013-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多