我在Python中研究了几种解决方案,包括lxml,BeautifulSoup和Scrapy。

URL是: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类,然后是其中的img类“ photo”。

我想下载该图像(注意:我将继续下载几个)。我已经研究了csselector和xpath(并不总是受支持,例如,后者带有BeautifulSoup)-但是我似乎无法下载它,在示例中,我发现人们可以访问img的标签来获取URL的href,这里不是这样。

最佳答案

我假设您已经有一个正在运行的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


那应该将每个符合您指定规则的映像下载到项目文件夹中。

干杯。

关于python - 来自CSS类的Python抓取图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27552497/

10-10 00:20
查看更多