5

我需要在与此类似的 HTML 代码中找到一张图片:

...
<a href="/example/1"> 
    <img id="img" src="http://example.net/example.jpg" alt="Example" />
</a>
...

我正在使用 lxml 和请求。

这是代码:

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

建议?

4

2 回答 2

4

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

于 2012-07-19T20:47:55.117 回答
1
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)
于 2012-07-19T22:42:44.207 回答