这是我的代码:

import urllib2.request

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

任何帮助吗?


当前回答

注意: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的更多详细信息。点击这个链接。

其他回答

而不是使用:

import urllib2

在python3中使用下面的代码

import urllib.request as urllib2

最简单的解决方案:

在Python 3.x中:

import urllib.request
url = "https://api.github.com/users?since=100"
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
data_content = response.read()
print(data_content)

这在python3中很有效:

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

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)

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

在python 3中,获取文本输出:

import io
import urllib.request

response = urllib.request.urlopen("http://google.com")
text = io.TextIOWrapper(response)