带有lxml的Python下载图像 [英] Python download image with lxml
本文介绍了带有lxml的Python下载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要用类似于以下内容的HTML代码找到一张图片:
I need to find an image in a HTML code similar to this one:
...
<a href="/example/1">
<img id="img" src="http://example.net/example.jpg" alt="Example" />
</a>
...
我正在使用lxml和请求.
I am using lxml and requests.
这是代码:
import lxml
from lxml import html
import requests
url = 'http://www.example.com'
r = requests.get(url)
tree = lxml.html.fromstring(r.content)
img = tree.get_element_by_id("img")
f = open("image.jpg",'wb')
f.write(requests.get(img['src']).content)
但是我遇到一个错误:
Traceback (most recent call last):
File "/Users/Name/Documents/Python/Example/Script.py", line 13, in <module>
s = requests.get(img['src'])
File "/Library/Python/2.6/site-packages/lxml/lxml.etree.pyx", line 1052, in lxml.etree._Element.__getitem__ (src/lxml/lxml.etree.c:38272)
TypeError: 'str' object cannot be interpreted as an index
建议?
推荐答案
尝试 f.write(requests.get(img.attrib ['src']).content)
这篇关于带有lxml的Python下载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文