使用 Scrapy 和 Splash 在动态 JavaScript 网页中抓取图片

问题描述

我正在尝试抓取来自 this link 的高分辨率图像的链接,但只能通过点击中等大小的链接来检查图像的高分辨率版本在页面上,即点击“单击此处放大图像”(在页面上,它是土耳其语)。
然后我可以使用 Chrome 的“开发者工具”检查它并获取 xpath/css 选择器。到目前为止一切都很好。

但是,您知道在 JS 页面中,您无法键入 response.xpath("//blah/blah/@src")获取一些数据。我安装了 Splash(使用 Docker pull)并配置了我的 Scrapy setting.py 文件等以使其工作(这个 YouTube link 有帮助。除非你想学习如何做,否则不需要访问链接)。 ...它适用于其他 JS 网页!

只是...我无法通过这个“点击这里放大图像!” 事情并获得响应。它给了我 null 响应。

这是我的代码

import scrapy
#import json
from scrapy_splash import SplashRequest

class TryMe(scrapy.Spider):
    name = 'try_me'
    allowed_domains = ['arabam.com']

    def start_requests(self):
        start_urls = ["https://www.arabam.com/ilan/sahibinden-satilik-hyundai-accent/bayramda-arabasiz-kalmaa/17753653",]

        for url in start_urls:
            yield scrapy.Request(url=url,callback=self.parse,Meta={'splash': {'endpoint': 'render.html','args': {'wait': 0.5}}})
            # yield SplashRequest(url=url,callback=self.parse)  # this works too

    def parse(self,response):
        ## I can get this one's link successfully since it's not between js codes:
        #IMG_LINKS = response.xpath('//*[@id="js-hook-for-ing-credit"]/div/div/a/img/@src').get() 
        ## but this one just doesn't work:      
        IMG_LINKS = response.xpath("/html/body/div[7]/div/div[1]/div[1]/div/img/@src").get()
        print(IMG_LINKS)  # prints null :(
        yield {"img_links":IMG_LINKS}  # gives the items: img_links:null

我正在使用的 Shell 命令:
scrapy crawl try_me -O random_filename.jl

我正在尝试抓取链接的 Xpath:
/html/body/div[7]/div/div[1]/div[1]/div/img

Image of this Xpath/link

我实际上可以在我的开发者工具窗口网络标签上看到我想要的链接,当我点击放大它但我不知道如何从该标签页中>抓取链接

可能的解决方案:我还将尝试获取我的响应的整个乱码正文,即 response.text 并应用正则表达式(例如以 { 开头) {1}} 并以 https://...) 结尾。这肯定是大海捞针,但听起来也很实用。

谢谢!

解决方法

据我所知,您想找到主图片链接。我检查了页面,它在元元素之一中:

<meta itemprop="image" content="https://arbstorage.mncdn.com/ilanfotograflari/2021/06/23/17753653/3c57b95d-9e76-42fd-b418-f81d85389529_image_for_silan_17753653_1920x1080.jpg">

你可以得到什么

>>> response.css('meta[itemprop=image]::attr(content)').get()
'https://arbstorage.mncdn.com/ilanfotograflari/2021/06/23/17753653/3c57b95d-9e76-42fd-b418-f81d85389529_image_for_silan_17753653_1920x1080.jpg'

您不需要为此使用飞溅。如果我用飞溅检查网站,arabam.com 会给出权限被拒绝的错误。我建议不要在这个网站上使用飞溅。

为了更好地解决所有图像,您可以解析 javascript。在源代码中加载了 js 的图像数组。

enter image description here

要接触该 javascript,请尝试:

  response.css('script::text').getall()[14]

这将为您提供包含图像数组的整个 javascript 字符串。您可以使用 js2xml 等内置库对其进行解析。

在此处查看如何使用它https://github.com/scrapinghub/js2xml。如果还有问题,可以提问。祝你好运