如何使用scrky获得所有img src



尝试在碎屑壳中执行

>>>scrapy shell 'https://www.trendyol.com/trendyolmilla/cok-renkli-desenli-elbise-twoss20el0573-p-36294862'
>>> response.css("div.slick-slide img").xpath("@src").getall()

输出为:

['/Content/images/defaultThumb.jpg', '/Content/images/defaultThumb.jpg', '/Content/images/defaultThumb.jpg', '/Content/images/defaultThumb.jpg', '/Content/images/defaultThumb.jpg', 'https://cdn.dsmcdn.com/mnresize/415/622/ty124/product/media/images/20210602/12/94964657/64589619/1/1_org_zoom.jpg', 'https://cdn.dsmcdn.com/mnresize/415/622/ty124/product/media/images/20210602/12/94964657/64589619/1/1_org_zoom.jpg']

只收集一张图片,但在提供的链接中有5张图片。请帮我解决这个问题。如何找到所有的图像src。

解释

实际上,您正试图从只包含一个链接的HTML标记中获取数据。为了获取所有链接,您必须从script标签中获取。

这将返回json字符串,该字符串将存储在文本变量中

text = response.xpath("//p/script[contains(@type,'application/ld+json')]/text()").extract_first()

加载它以转换为python字典

json_text = json.loads(text)

现在,通过按键json_text.get('image')来获取图像。

代码

在scrapy上执行此代码。输出将给你所有的5个链接

from scrapy import Request

class Trendyol(scrapy.Spider):
name = 'test'
def start_requests(self):
url = 'https://www.trendyol.com/trendyolmilla/cok-renkli-desenli-elbise-twoss20el0573-p-36294862'
yield Request(url=url, callback=self.parse)
def parse(self, response):
text = response.xpath("//p/script[contains(@type,'application/ld+json')]/text()").extract_first()
json_text = json.loads(text)
print(json_text.get('image'))

最新更新