账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    scrapy爬取图片,遇到https://demo?wx_fmt=jpeg情况,无法爬取
    81
    0

    原连接:https://mmbiz.qlogo.cn/mmbiz/...
    使用的是scrapy的ImagesPipeline

    class ImgPipeline(ImagesPipeline):
        """
        scrapy图片处理管道
        """
    
        # 请求图片
        def get_media_requests(self, item, info):
            content = str(item['content'])
            match = re.findall(r'src="(http|https?://.*?)"', content)
            item['img_links'] = match
            for img_link in item['img_links']:
                yield scrapy.Request(img_link)
    
        # 请求完成后
        def item_completed(self, results, item, info):
            image_paths = [x['path'] for ok, x in results if ok]
            if not image_paths:
                raise DropItem("Item contains no image")
            item['img_paths'] = image_paths
            return item

    异常

    2017-12-22 10:06:47 [scrapy.pipelines.files] ERROR: File (unknown-error): Error processing file from <GET http://mmbiz.qpic.cn/mmbiz/AWbBdRJFaKQ4vb5qV2Nyc41VAuLmiaqePia7hI0uMlE3KRbZEOsaB4jAPdibnzBAmKp1aCiateeXGXoicsAfMugCVog/640?wx_fmt=png&;amp;tp=webp&amp;wxfrom=5&amp;wx_lazy=1> referred in <None>
    Traceback (most recent call last):
      File "C:\Users\zjx\Anaconda3\lib\site-packages\twisted\internet\defer.py", line 1386, in _inlineCallbacks
        result = g.send(result)
      File "C:\Users\zjx\Anaconda3\lib\site-packages\scrapy\core\downloader\middleware.py", line 43, in process_request
        defer.returnValue((yield download_func(request=request,spider=spider)))
      File "C:\Users\zjx\Anaconda3\lib\site-packages\twisted\internet\defer.py", line 1363, in returnValue
        raise _DefGen_Return(val)
    twisted.internet.defer._DefGen_Return: <200 http://mmbiz.qpic.cn/mmbiz/AWbBdRJFaKQ4vb5qV2Nyc41VAuLmiaqePia7hI0uMlE3KRbZEOsaB4jAPdibnzBAmKp1aCiateeXGXoicsAfMugCVog/640?wx_fmt=png&;amp;tp=webp&amp;wxfrom=5&amp;wx_lazy=1>
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "C:\Users\zjx\Anaconda3\lib\site-packages\scrapy\pipelines\files.py", line 356, in media_downloaded
        checksum = self.file_downloaded(response, request, info)
      File "C:\Users\zjx\Anaconda3\lib\site-packages\scrapy\pipelines\images.py", line 98, in file_downloaded
        return self.image_downloaded(response, request, info)
      File "C:\Users\zjx\Anaconda3\lib\site-packages\scrapy\pipelines\images.py", line 102, in image_downloaded
        for path, image, buf in self.get_images(response, request, info):
      File "C:\Users\zjx\Anaconda3\lib\site-packages\scrapy\pipelines\images.py", line 115, in get_images
        orig_image = Image.open(BytesIO(response.body))
      File "C:\Users\zjx\Anaconda3\lib\site-packages\PIL\Image.py", line 2519, in open
        % (filename if filename else fp))
    OSError: cannot identify image file <_io.BytesIO object at 0x000001842C76EFC0>

    目前分析问题出现的原因是,该链接返回的是图片的base64,scrapy不能识别

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 众羽 普通会员 1楼

      在Scrapy中,当你遇到一个URL,该URL使用了某种特定的格式(如JPEG)作为文件扩展名时,通常需要进行一些额外的处理才能爬取这些图片。以下是一些可能的步骤:

      1. 检查图片的扩展名:首先,你需要检查图片的扩展名是否与你预期的格式相符。在Scrapy的settings.py文件中,你可以添加以下配置:

      python FEED_FORMAT = 'jpeg'

      这将使Scrapy在爬取图片时,如果图片的扩展名为jpeg,它将使用FEED_FORMAT设置为'jpeg'。如果你的图片扩展名不是'jpeg',那么Scrapy将无法正确解析该URL,并且可能无法爬取图片。

      1. 检查图片的URL:确保你已正确解析了包含图片的URL。如果URL中包含了图片的文件名,你可能需要将'http'替换为'https'。例如:

      python url = 'https://demo?wx_fmt=jpeg&url=' + url

      如果URL中没有包含图片的文件名,你需要在爬取图片时,使用一些额外的代码来处理图片的路径。Scrapy提供了一个parse函数,可以处理网页中的HTML元素和子元素,包括img元素,其中src属性包含了图片的URL。你可以使用parse函数来解析这个URL并获取图片的src属性,然后将其转换为本地文件路径,例如:

      ```python import scrapy

      class ImageSpider(scrapy.Spider): name = 'image_spider' allowed_domains = ['yourwebsite.com'] start_urls = ['https://demo?wx_fmt=jpeg']

      def parse(self, response):
          img_url = response.css('img[src]::attr(src)').get()
          if img_url:
              # 通过URL解析图片
              image_url = response.urljoin(img_url)
              # 获取图片的本地路径
              local_path = os.path.join(self._spider_dir, image_url.split('/')[-1])
              # 打开图片文件
              with open(local_path, 'rb') as f:
                  # 加载图片数据
                  img_data = f.read()
              yield {
                  'url': img_url,
                  'local_path': local_path,
                  'content': img_data
              }
      

      ```

      在这个例子中,我们首先使用CSS选择器img[src]::attr(src)找到了包含图片URL的img元素,然后使用response.urljoin函数将图片URL转换为本地路径。接着,我们使用open函数打开图片文件,读取其数据,最后将数据输出为字典并返回。

      注意,这只是一个基本的例子,实际的爬取过程可能会根据你的具体需求和URL格式有所不同。例如,你可能需要处理图片的尺寸、编码方式、背景信息等。另外,确保你已正确设置图片的HTTP头,例如Content-Type'image/jpeg',以确保Scrapy能够正确解析和处理图片。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部