Python 3.2.3运行错误

时间:2012-10-17 08:20:39

标签: python python-3.x urllib

我使用此代码在ip地址中获取组织

import urllib 
import lxml.html as lh
req= urllib.Request("http://www.ip-address.com/ip_tracer/157.123.22.11", headers={'User-Agent' : "Magic Browser"})
html = urllib.urlopen(req).read()
doc = lh.fromstring(html)
print (''.join(doc.xpath('.//*[@class="odd"]')[-1].text_content().split()))

我的python是3.2.3,它显示

  Traceback (most recent call last):
  File "ext.py", line 3, in <module>
  req= urllib.Request("http:// www.ip-address.com/ip_tracer/157.123.22.11", headers={'User-Agent' : "Magic Browser"})
  AttributeError: 'module' object has no attribute 'Request'

如何解决它。谢谢,

1 个答案:

答案 0 :(得分:3)

如果您想使用urllib.request.Request,请按以下方式导入:

import urllib.request

r = urllib.request.Request(...)
html = urllib.request.urlopen(r).read()

如果urllib.request中不需要任何其他内容,则只能导入Request

from urllib.request import Request

r = Request(...)