python-3.x - 如何用scrapy保存图片

标签 python-3.x bash scrapy

我从 https://www.topgear.com/car-reviews/ferrari/laferrari 中提取了图像链接在bash中使用scrapy,有没有简单的方法可以在没有管道的情况下保存它们?

scrapy shell https://www.topgear.com/car-reviews/ferrari/laferrari
response.xpath('//div[@class="carousel__content-inner"]//img/@srcset').extract()
['https://www.topgear.com/sites/default/files/styles/fit_980x551/public/cars-car/carousel/2015/02/buyers_guide_-_laf_-_front.jpg?itok=KiD7ErMe 980w',
 'https://www.topgear.com/sites/default/files/styles/fit_980x551/public/cars-car/carousel/2015/02/buyers_guide_-_laf_-_rear.jpg?itok=JMYaaJ5L 980w',
 'https://www.topgear.com/sites/default/files/styles/fit_980x551/public/cars-car/carousel/2015/02/buyers_guide_-_laf_-_interior.jpg?itok=4Z0zIdH_ 980w',
 'https://www.topgear.com/sites/default/files/styles/fit_980x551/public/cars-car/carousel/2015/02/buyers_guide_-_laf_-_side.jpg?itok=OKl2MOJ2 980w']

感谢您的帮助。

最佳答案

您可以使用scrapy选择器https://docs.scrapy.org/en/latest/topics/selectors.html 和请求库:

from scrapy.selector import Selector
import requests
from tqdm import tqdm

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}
response = requests.get('https://www.topgear.com/car-reviews/ferrari/laferrari', headers=headers)
links = Selector(text=response.text).xpath('//div[@class="carousel__content-inner"]//img/@srcset').getall()

for i, image_url in tqdm(enumerate(links)):
    try:
        response = requests.get(image_url, headers=headers)
    except:
        pass
    else:
        if response.status_code == 200:
            with open('{:02}.jpg'.format(i), 'wb') as f:
                f.write(response.content)

关于python-3.x - 如何用scrapy保存图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59734613/

相关文章:

python - 如何在 Python f 字符串中指定文字字符串的宽度?

python-3.x - 当模型包含 UDT 集时,Cassandra python 驱动程序 ORM 崩溃

bash - zgrep - 列出匹配的文件名

bash - 如何使用 Bash 递归地创建不存在的子目录?

python - 社区中在同一代码库中使用 python 2.x 和 3.x 的首选方法是什么?

r - MSapriori 和 CARapriori 算法在 Python 或 R 中的实现

git - 切换分支时调用外部命令

python - xpath:字符串操作

python - 将 scrapy 项目导出到不同的文件

scrapy - 在scrapy中嵌套项目数据的正确方法