【问题标题】:My scraper throws error instead of downloading images我的刮刀抛出错误而不是下载图像
【发布时间】:2017-05-02 13:17:39
【问题描述】:

我制作了一个从网站下载图像的刮板。但是,当我运行它时,它会抛出错误显示:[raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError:HTTP 错误 403]。我也在其他网站上使用这种方法来抓取图像,但没有遇到任何问题。我无法弄清楚为什么会出现此错误以及解决方法是什么。希望有人调查一下。

import requests
import urllib.request
from lxml import html

def PictureScraping():
    url = "https://www.yify-torrent.org/search/1080p/"
    response = requests.get(url)
    tree = html.fromstring(response.text)
    titles = tree.xpath('//div[@class="movie-image"]')
    for title in titles:
        Pics = "https:" + title.xpath('.//img/@src')[0]
        urllib.request.urlretrieve(Pics, Pics.split('/')[-1])
PictureScraping()

【问题讨论】:

  • 它是403 HTTP 代码,又名未授权。您肯定会被发现为爬虫,因此被列入黑名单。您必须使用代理和用户代理 http 标头来绕过这种行为

标签: python web-crawler


【解决方案1】:

您需要使用与获取初始页面相同的网络抓取会话来下载图像。工作代码:

import requests
from lxml import html


def PictureScraping():
    url = "https://www.yify-torrent.org/search/1080p/"
    with requests.Session() as session:
        response = session.get(url)

        tree = html.fromstring(response.text)
        titles = tree.xpath('//div[@class="movie-image"]')
        for title in titles:
            image_url = title.xpath('.//img/@src')[0]
            image_name = image_url.split('/')[-1]
            print(image_name)
            image_url = "https:" + image_url

            # download image
            response = session.get(image_url, stream=True)
            if response.status_code == 200:
                with open(image_name, 'wb') as f:
                    for chunk in response.iter_content(1024):
                        f.write(chunk)

PictureScraping()

【讨论】:

  • 天哪!它像魔术一样工作。谢谢先生,alecxe 为您提供有效的解决方案。
猜你喜欢
  • 2018-07-13
  • 2021-10-19
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2022-07-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多