我在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类的“球员形象足球运动衫”,然后是一个img里面的类“照片”。
我想下载该图片(注意:我会继续下载几张图片)。我已经查看了 csselector 和 xpath (并不总是支持,例如后者使用BeautifulSoup) - 但我似乎无法下载它并在示例中我'我发现人们访问img的标签以获取URL的 href ,但这不是这种情况。
答案 0 :(得分:1)
我假设您已经有一个正在运行的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
应该在项目文件夹中下载符合指定规则的每张图片。
干杯。
答案 1 :(得分:0)
下载图片的最简单方法是使用urllib的urlretrieve方法。它需要一个可选的文件名参数,您可以在其中指定下载文件的路径和名称(默认情况下,我相信它会自动生成一个名称并将其放在当前目录中)。
对于您的html代码段,您可以执行以下操作:
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**)