这是我的代码:

import urllib2.request

response = urllib2.urlopen("http://www.google.com")
html = response.read()
print(html)

任何帮助吗?


当前回答

对于使用Python 2(测试版本2.7.3和2.6.8)和Python 3(3.2.3和3.3.2+)的脚本,请尝试:

#! /usr/bin/env python

try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

html = urlopen("http://www.google.com/")
print(html.read())

其他回答

注意:urllib2在Python 3中不再可用

您可以尝试下面的代码。

import urllib.request 
res = urllib.request.urlopen('url')
output = res.read()
print(output)

你可以得到更多关于urllib的信息。从此链接请求。

使用:urllib3

import urllib3
http = urllib3.PoolManager()
r = http.request('GET', 'url')
print(r.status)
print( r.headers)
print(r.data)

如果您想了解urllib3的更多详细信息。点击这个链接。

Python 3:

import urllib.request

wp = urllib.request.urlopen("http://google.com")
pw = wp.read()
print(pw)

Python 2:

import urllib
import sys

wp = urllib.urlopen("http://google.com")
for line in wp:
    sys.stdout.write(line)

虽然我已经分别测试了两个代码的版本。

上面的方法在3.3中对我不起作用。试试这个(YMMV,等等)

import urllib.request
url = "http://www.google.com/"
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
print (response.read().decode('utf-8'))

这在python3中很有效:

import urllib.request
htmlfile = urllib.request.urlopen("http://google.com")
htmltext = htmlfile.read()
print(htmltext)

而不是使用:

import urllib2

在python3中使用下面的代码

import urllib.request as urllib2