Python download image with lxml

情到浓时终转凉″ 提交于 2021-02-08 15:48:11

问题


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>
...

I am using lxml and requests.

Here is the code:

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)

But i am getting an error:

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

Suggestions?


回答1:


try f.write(requests.get(img.attrib['src']).content)




回答2:


import lxml.html
import requests

url = 'http://www.example.com/'
tree = lxml.html.parse(url)
img = tree.get_element_by_id('img')
img_url = img.attrib['src']

with open('image.jpg', 'wb') as outf:
    data = requests.get(img_url).content
    outf.write(data)


来源:https://stackoverflow.com/questions/11566596/python-download-image-with-lxml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!