python打开网页获取网页内容方法总结

来源:互联网 发布:手机画图软件排行 编辑:程序博客网 时间:2024/06/05 17:09

在学习Python爬虫的过程中,总会遇到要获取网页内容的时候,下面就对如何获取网页内容进行总结。

方法一:

import urlliburl="http://www.baidu.com" #这里是需要获取的网页content=urllib.open(url).read() #使用urllib模块获取网页内容print content #输出网页的内容 功能相当于查看网页源代码

方法二:

import urllib2from bs4 import BeautifulSoup #这里需要导入BeautifulSoup url="http://www.baidu.com"content=urllib2.urlopen(url)soup=BeautifulSoup(content) #将网页内容转化为BeautifulSoup 格式的数据print soup

方法三:

import requestscontent=requests.get(url).contentprint content

这里是使用的python的requests模块获取网页的内容。

方法四:

import codecs  #导入codecs模块f=codecs.open(url,"r","utf-8")   #使用codecs函数以打开的方式打开url 设置默认的编码方式为utf-8content=f.read()f.close()print content

这里是使用的python的codecs模块。

原创粉丝点击