这是我的代码:

import urllib2.request

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

任何帮助吗?


当前回答

最简单的解决方案:

在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)

其他回答

而不是使用:

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)

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

import io
import urllib.request

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

这在python3中很有效:

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

正如urllib2文档中所述:

在Python 3中,urllib2模块被拆分为几个名为urllib的模块。请求和urllib.error。2to3工具将在将源代码转换为Python 3时自动适应导入。

所以你应该说

from urllib.request import urlopen
html = urlopen("http://www.google.com/").read()
print(html)

您现在编辑的代码示例是不正确的,因为您说的是urllib.urlopen(“http://www.google.com/”)而不是urlopen(“http://www.google.com/”)。