【问题标题】:Python Scrape Images From CSS ClassPython 从 CSS 类中抓取图像
【发布时间】:2015-02-17 14:09:03
【问题描述】:

我已经在 Python 中查看了一些解决方案,包括 lxml、BeautifulSoup 和 Scrapy。

网址是:https://uk.eurosport.yahoo.com/football/players/hugo-lloris/

<div class="player-image soccer-jersey" id="yui_3_16_0_1_1418920336731_663">
            
  <img src="https://s1.yimg.com/bt/api/res/1.2/tJcByeD1uUzpRu9blmsOZA--  /YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTE3MDtxPTc1O3c9MTgw/http://l.yimg.com/j/assets/i/us/sp/v/soccer/worldcup/players/374980.1.jpg" width="180" height="170" alt="H. Lloris" title="" class="photo" id="yui_3_16_0_1_1418920336731_664">

</div>

我们有一个 div 类“player-image football-jersey”,然后在里面有一个 img 类“photo”。

我想下载该图像(注意:我会继续下载几个)。我已经查看了 csselectorxpath (并不总是支持,例如后者使用 BeautifulSoup) - 但我似乎无法下载它,在示例中我'发现有人访问img的标签来获取URL的href,这里不是这样的。

【问题讨论】:

  • 任何答案对您有帮助吗?这个社区通过提问者和回答者之间的双向反馈发挥作用。您应该投票或选择(单击绿色复选标记)任何对您有用的回复。
  • @MagentaNova 我没有投票的声誉,但我点击了无色勾号。干杯。

标签: python python-2.7 web web-scraping web-crawler


【解决方案1】:

下载图片最简单的方法是使用 urllib 的urlretrieve 方法。它带有一个可选的文件名参数,您可以在其中指定下载文件的路径和名称(默认情况下,我相信它会自动生成一个名称并将其放在当前目录中)。

对于您的 html sn-p,您可以执行以下操作:

from bs4 import BeautifulSoup as BS
from urllib import urlretrieve

soup = BS(**the html you scraped**) 
imgTag = soup.find('img',id='yui_3_16_0_1_1418920336731_664')
imgSrc = imgTag['src'] # in this case, the source is the full url
# but in other cases it may be relative path, in which case you would append it
# to the base url
urlretrieve(imgSrc,filename=**path that you want to save the image to**)

【讨论】:

  • 如果我明白你的意思,@djdavies7,它是不灵活的,因为它将'src'属性视为一个完整的url?您可以使用 url 解析中的 urljoin 方法,将基本 url 和 src 路径作为两个参数,来获取 urlretrieve 的完整 url。
  • 您处理的是特定 ID 而不是所有 URL 都相同的 CSS 类,因此获取下一个 ID(我说过我会抓取几个)会很麻烦。干杯。
【解决方案2】:

我假设您已经有一个正在运行的 python 环境,并且为此代码安装了所有必要的依赖项。

在命令行界面上,创建一个 Scrapy 项目:

scrapy startproject yuiImage

这将在您的当前目录中创建一个 yuiImage 项目文件夹。

然后,在您的项目中的 yuiImage/spiders 文件夹中创建一个 yuiimage_spider.py 文件文件夹:

import re, scrapy
from urllib import urlretrieve

class YuiimageSpider(scrapy.Spider):
    name = "yuiimage"
    allowed_domains = ["yahoo.com"]
    start_urls = [
        "https://uk.eurosport.yahoo.com/football/players/hugo-lloris/"
    ]

    def parse(self, response):
        imageSrcs = response.xpath("//div[contains(@class, 'player-image') and contains(@class, 'soccer-jersey')]/img[@style and contains(@style, 'yimg.com') and contains(@class, 'photo')]/@style").extract()
        for src in imageSrcs:
            imgUrl = re.search('http\:.*', re.search('[^(].*\(\'(.*)\'\);', src).group(1)).group(0)
            urlretrieve(imgUrl, imgUrl.split("/").pop())

然后在您的项目文件夹中运行以下命令:

scrapy crawl yuiimage

这应该下载符合您项目文件夹中指定规则的每个图像。

干杯。

【讨论】:

  • 这是最好的解决方案,因为当我想抓取其他图像时,使用 xpath 可以让事情变得更加灵活,而你在逻辑上已经预见到我想要这样做。
猜你喜欢
  • 1970-01-01
  • 2021-01-27
  • 2020-11-14
  • 1970-01-01
  • 2017-12-09
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 2015-06-08
相关资源
最近更新 更多