J'ai besoin de trouver une image dans un code HTML similaire à celui-ci :
...
<a href="stackoverflow.com/example/1">
<img id="img" src="http://example.net/example.jpg" alt="Example" />
</a>
...
J'utilise lxml et requests.
Voici le 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)
Mais je reçois une erreur :
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
Des suggestions ?