python获取页面的方法:1、使用urllib模块获取网页内容;2、使用urllib2模块获取页面内容;3、使用requests模块获取页面内容;4、使用codecs模块获取页面内容。
在学习python爬虫的过程中,总会遇到要获取网页内容的时候,下面就对如何获取网页内容进行总结。
方法一:
>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 Scrapy 网络爬虫实战视频教程



