在网页上抓取一个jpg文件,然后使用python保存它

2024-09-30 14:23:58 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我试着从古驰网站上抓取jpg图片。以这个为例。在

http://www.gucci.com/images/ecommerce/styles_new/201501/web_full/277520_F4CYG_4080_001_web_full_new_theme.jpg

我试过了urllib.url检索,但这不起作用,因为Gucci阻塞了这个函数。所以我想使用请求来获取图像的源代码,然后将其写入.jpg文件。在

image = requests.get("http://www.gucci.com/images/ecommerce/styles_new/201501/web_full/277520_F4CYG_4080_001_web_full_new_theme.jpg").text.encode('utf-8')

我对它进行编码,因为如果我不编码,它会一直告诉我gbk不能对字符串进行编码。在

然后:

^{pr2}$

看起来不错吧?但结果是——jpg文件无法打开。没有图像!Windows告诉我jpg文件已损坏。在

有什么问题吗?在

  1. 我在想,也许当我刮图像时,我丢失了一些信息,或者一些字符被错误地刮了。但是我怎么才能知道是哪一个呢?

  2. 我在想也许有些信息是通过编码丢失的。但如果我不编码,我甚至不能打印它,更不用说把它写入文件了。

会出什么问题?在


Tags: 文件图像comwebhttp编码newwww
2条回答

JPEG文件不是文本,而是二进制数据。所以您需要使用request.content属性来访问它。

下面的代码还包含一个get_headers()函数,当您浏览一个网站时,这个函数非常方便。

import requests

def get_headers(url):
    resp = requests.head(url)
    print("Status: %d" % resp.status_code)
    resp.raise_for_status()
    for t in resp.headers.items():
        print('%-16s : %s' % t)

def download(url, fname):
    ''' Download url to fname '''
    print("Downloading '%s' to '%s'" % (url, fname))
    resp = requests.get(url)
    resp.raise_for_status()
    with open(fname, 'wb') as f:
        f.write(resp.content)

def main():
    site = 'http://www.gucci.com/images/ecommerce/styles_new/201501/web_full/'
    basename = '277520_F4CYG_4080_001_web_full_new_theme.jpg'
    url = site + basename
    fname = 'qtest.jpg'

    try:
        #get_headers(url)
        download(url, fname)
    except requests.exceptions.HTTPError as e:
        print("%s '%s'" % (e, url))

if __name__ == '__main__':
    main()

我们调用.raise_for_status()方法,以便get_headers()和{}在出错时引发异常;我们在main()中捕获异常并打印相关信息。

我不确定您使用encode的目的。你不是在处理文本,而是在处理图像。您需要以二进制数据而不是文本的形式访问响应,并使用图像处理函数而不是文本函数。试试这个:

from PIL import Image
from io import BytesIO
import requests

response = requests.get("http://www.gucci.com/images/ecommerce/styles_new/201501/web_full/277520_F4CYG_4080_001_web_full_new_theme.jpg")
bytes = BytesIO(response.content)
image = Image.open(bytes)
image.save("1.jpg")

注意使用response.content而不是{}。您需要安装PIL或枕头才能使用Image模块。BytesIO包含在python3中。

或者,您可以直接将数据保存到磁盘,而不必查看其中的内容:

^{pr2}$

相关问题 更多 >