python获取网页失败的解决方法:首先导入【urllib】模块;然后将需要获取的网页返回给url;再使用【urllib】模块获取网页内容;最后输出网页的内容即可获取网页。
方法一:import urllib
url="http://www.baidu.com" #这里是需要获取的网页
content=urllib.open(url).read() #使用urllib模块获取网页内容
print content #输出网页的内容 功能相当于查看网页源代码
方法二:import urllib2
from bs4 import BeautifulSoup #这里需要导入BeautifulSoup
url="http://www.baidu.com"
content=urllib2.urlopen(url)
soup=BeautifulSoup(content) #将网页内容转化为BeautifulSoup 格式的数据
print soup
方法三:import requests
content=requests.get(url).content
print content
这里是使用的python的requests模块获取网页的内容。
方法四:import codecs #导入codecs模块
f=codecs.open(url,"r","utf-8") #使用codecs函数以打开的方式打开url 设置默认的编码方式为utf-8
content=f.read()
f.close()
print content
这里是使用的python的codecs模块。