您的位置:首页 > 编程语言 > Python开发

Python3 BeautifulSoup4结合urllib简单使用

2013-12-15 15:00 429 查看
1、使用urllib下载网页

2、构造BeautifulSoup对象

3、剖析文档

代码示例:【需要注意import模块版本的区别】

import urllib.request
from bs4 import BeautifulSoup
import re

def getgxnu():
url="http://www.gxnu.edu.cn/default.html"
data=urllib.request.urlopen(url).read()
page_data=data.decode('GBK')
'''print(page_data)'''
soup=BeautifulSoup(page_data)
#for link in soup.findAll('a',target='_self'):#get all links of gxnu index
#    print(link)
for link in soup.findAll('a',href=re.compile('http://\\S+/type/\\d+.html')):#使用正则表达式
print(link['href'],link.contents)

#函数调用
getgxnu()


输出结果:

>>> http://www.gxnu.edu.cn/type/010400000102.html ['\n', <span>学校概况</span>] http://www.gxnu.edu.cn//type/010400000102.html ['学校简介'] http://www.gxnu.edu.cn/type/01040000010202.html ['学校沿革'] http://www.gxnu.edu.cn/type/01040000010203.html ['学校领导'] http://www.gxnu.edu.cn/type/01040000010204.html ['校园风光'] http://www.gxnu.edu.cn/type/01040000010205.html ['校园地图'] http://www.gxnu.edu.cn/type/01040000010206.html ['校歌 校训 校徽'] http://www.gxnu.edu.cn/type/01040000010207.html ['学校视觉形象识别系统'] http://www.gxnu.edu.cn/type/01040000010208.html ['校史资料'] http://www.gxnu.edu.cn/type/010400000103.html ['\n', <span>机构设置</span>] http://www.gxnu.edu.cn/type/010400000103.html ['教学单位'] http://www.gxnu.edu.cn/type/010400000103.html ['管理部门'] http://www.gxnu.edu.cn/type/010400000103.html ['业务部门'] http://www.gxnu.edu.cn/type/010400000103.html ['附属单位'] http://www.gxnu.edu.cn/type/010400000104.html ['\n', <span>学术研究</span>] http://www.gxnu.edu.cn/type/01040000010401.html ['科研管理'] http://www.gxnu.edu.cn/type/01040000010402.html ['科研机构'] http://www.gxnu.edu.cn/type/01040000010403.html ['重点学科'] http://www.gxnu.edu.cn/type/01040000010404.html ['重点实验室'] http://www.gxnu.edu.cn/type/01040000010405.html ['学术刊物'] http://www.gxnu.edu.cn/type/010400000105.html ['\n', <span>人才队伍</span>] http://www.gxnu.edu.cn/type/010400000106.html ['\n', <span>招生就业</span>] http://www.gxnu.edu.cn/type/01040000010601.html ['招生信息'] http://www.gxnu.edu.cn/type/01040000010602.html ['就业信息'] http://www.gxnu.edu.cn/type/01040000010603.html ['就业指导'] http://www.gxnu.edu.cn/type/010400000107.html ['\n', <span>图书档案</span>] http://www.gxnu.edu.cn/type/01040000010801.html ['\n', <span>公共服务</span>] http://www.gxnu.edu.cn/type/01040000010801.html ['教学服务'] http://www.gxnu.edu.cn/type/01040000010805.html ['其他'] http://www.gxnu.edu.cn/type/010400000111.html ['\n', <span>校园文化</span>] http://www.gxnu.edu.cn/type/01040000011101.html ['学生社团'] http://www.gxnu.edu.cn/type/010400000112.html ['\n', <span>ENGLISH</span>]
>>>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: