使用Scrapy从图片中抓取网址

时间:2018-09-14 06:03:24

标签: python python-3.x if-statement xpath scrapy

我正在尝试从this website刮取图像的链接

出现在页面早期的图像的URL为

<img src="//sc01.alicdn.com/kf/HTB1jvmMXmtYBeNjSspkq6zU8VXa3/Closed-Cell-Expanded-Perlite-Bulk-Expanded-Perlite.jpg_300x300.jpg" alt="Closed Cell Expanded Perlite Bulk Expanded Perlite Price" />

稍后显示的图像的网址为

<img src="//img.alicdn.com/tfs/TB1S_7kkY5YBuNjSspoXXbeNFXa-700-700.jpg_350x350.jpg" data-src="//sc01.alicdn.com/kf/HTB1IXB5abwTMeJjSszfq6xbtFXaQ/Expanded-Perlite-for-Agriculture.jpg_300x300.jpg" alt="Expanded Perlite for Agriculture" />

第二种情况下的src包含指向通用图像的链接,该链接出现在页面的实际图像加载之前,而data_src是要剪贴的实际URL。

所以我尝试使用这段代码使用三元表达式(如果有的话)来抓取网址。

我的代码

import scrapy

class AlibabaSpider(scrapy.Spider):
    name = 'alibaba'
    allowed_domains = ['alibaba.com']
    start_urls = ['https://www.alibaba.com/catalog/agricultural-growing-media_cid144?page=1']

def parse(self, response):
    url = '//img.alicdn.com/tfs/TB1S_7kkY5YBuNjSspoXXbeNFXa-700-700.jpg_350x350.jpg'
    for products in response.xpath('//div[contains(@class, "m-gallery-product-item-wrap")]'):
        img_url_datasrc = products.xpath('.//div[@class="offer-image-box"]/img/@data-src').extract_first()
        img_url_src = products.xpath('.//div[@class="offer-image-box"]/img/@src').extract_first()
        item = {
        'product_name': products.xpath('.//h2/a/@title').extract_first(),
        'image_url': img_url_datasrc if img_url_src == url else img_url_src, #This is problem
        }
        yield item

结果不是我想要的那种。

编辑

查询结果:

img_url_datasrc if img_url_src == url else img_url_src

enter image description here

2 个答案:

答案 0 :(得分:0)

'image_url': img_url_datasrc if img_url_src == url else img_url_datasrc, #This is problem

这确实是问题所在,在两种情况下都将图像URL设置为img_url_datasrc。 您可能想要:

'image_url': img_url_datasrc if img_url_src == url else img_url_src,

答案 1 :(得分:0)

尝试这个=)

# -*- coding: utf-8 -*-
import scrapy


class AlibabaSpider(scrapy.Spider):
    name = 'alibaba'
    allowed_domains = ['alibaba.com']
    start_urls = ['https://www.alibaba.com/catalog/agricultural-growing-media_cid144?page=1']

    def parse(self, response):
        products = response.xpath('//div[@class="m-gallery-product-item-v2"]')
        img_data_url = ''

        for product in products:
            if product.xpath('.//div[@class="offer-image-box"]/img[contains(@src, "tfs")]'):
                img_data_url = product.xpath('.//div[@class="offer-image-box"]/img/@data-src').extract_first()
            else:
                img_data_url = product.xpath('.//div[@class="offer-image-box"]/img/@src').extract_first()

            item = {
                'product_name': product.xpath('.//h2/a/@title').extract_first(),
                'image_url': img_data_url,
            }
            yield item
  

result.json

result.json