好吧,我试着从古驰网站上抓取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文件已损坏。在
有什么问题吗?在
我在想,也许当我刮图像时,我丢失了一些信息,或者一些字符被错误地刮了。但是我怎么才能知道是哪一个呢?
我在想也许有些信息是通过编码丢失的。但如果我不编码,我甚至不能打印它,更不用说把它写入文件了。
会出什么问题?在
JPEG文件不是文本,而是二进制数据。所以您需要使用
request.content
属性来访问它。下面的代码还包含一个
get_headers()
函数,当您浏览一个网站时,这个函数非常方便。我们调用}在出错时引发异常;我们在
.raise_for_status()
方法,以便get_headers()
和{main()
中捕获异常并打印相关信息。我不确定您使用
encode
的目的。你不是在处理文本,而是在处理图像。您需要以二进制数据而不是文本的形式访问响应,并使用图像处理函数而不是文本函数。试试这个:注意使用}。您需要安装PIL或枕头才能使用
response.content
而不是{Image
模块。BytesIO
包含在python3中。或者,您可以直接将数据保存到磁盘,而不必查看其中的内容:
^{pr2}$相关问题 更多 >
编程相关推荐