这是我的代码:

import urllib2.request

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

任何帮助吗?


当前回答

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

import io
import urllib.request

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

其他回答

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

import io
import urllib.request

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

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

这在python3中很有效:

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

上面的方法在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'))