【问题标题】:how I can get all images if i'm using beautiful soup?如果我用的是漂亮的汤,我怎么能得到所有的图像?
【发布时间】:2013-12-08 22:29:16
【问题描述】:

如果是这样的代码,我如何获得图像:

<div class="galery-images">
<div class="galery-images-slide" style="width: 760px;">
<div class="galery-item galery-item-selected" style="background-image: url(/images/photo/1/20130206/30323/136666697057736800.jpg);"></div>

我想得到 136666697057736800.jpg 我写道:

 images = soup.select("div.galery-item")

我得到一个列表:

[<div class="galery-item galery-item-selected" style="background-image: url(/images/photo/1/20130206/30323/136666697057736800.jpg);"></div>, 
<div class="galery-item" style="background-image: url(/images/photo/1/20130206/30323/136013892671126300.jpg);" ></div>, 
<div class="galery-item" style="background-image: url(/images/photo/1/20130206/30323/136666699218876700.jpg);"></div>]

我不明白:如何获取所有图像?

【问题讨论】:

  • 您要下载图片吗?
  • 是的。我该怎么做?

标签: python html-parsing beautifulsoup


【解决方案1】:

Use regex or a css parser to extract the url,将host连接到URL的开头,最后像这样下载图片。

import urllib

urllib.urlretrieve("https://www.google.com/images/srpr/logo11w.png", "google.png")

【讨论】:

    【解决方案2】:

    为了让您的生活更轻松,您应该使用正则表达式:

    urls = []
    
    for ele in soup.find_all('div', attrs={'class':'galery-images-slide'}):
        pattern = re.compile('.*background-image:\s*url\((.*)\);')
        match = pattern.match(ele.div['style'])
        if match:
            urls.append(match.group(1))
    

    这通过查找属于父 div 的所有 divs 来工作(其类:'galery-images-slide')。然后,您可以使用正则表达式解析子 divs 以查找包含样式(其本身包含背景 URL)的任何内容。

    所以,从你上面的例子,这将输出:

    [u'/images/photo/1/20130206/30323/136666697057736800.jpg']
    

    现在,要下载指定的图片,在网址前附加站点名称,应该可以下载了。

    注意:

    这需要 Python 中的正则表达式模块 (re) 和 BeautifulSoup。 而且,我使用的正则表达式非常幼稚。但是,您可以根据需要进行调整以满足您的需要。

    【讨论】:

    • 谢谢。这是一个很好的解决方案,但不起作用。我只有一场比赛。但我想要嵌套
      中的所有图像
    • @Olga,您可以针对 x 个图像调整我的解决方案。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签