Unit1:Beautiful Soup
一、安装
https://www.crummy.com/software/BeautifulSoup/
管理员权限打开命令行:pip install beautifulsoup4(注意:使用pip install beautifulsoup 会失败)
安装测试:演示地址(http://python123.io/ws/demo.html)
网页源码:
<html><head><title>This is a python demo page</title></head>
<body>
<p class="title"><b>The demo python introduces several python courses.</b></p>
<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.</p>
</body></html>
import requests
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
from bs4 import BeautifulSoup
soup = BeautifulSoup(demo, "html.parser") #选择html解析器
#from bs4 import BeautifulSoup
#soup = BeautifulSoup('<p>data<p>', "html.parser")
print(soup.title)
print(soup.a)
print(soup.prettify())
soup.a.name
soup.a.parent.name
二、Beautiful Soup库的理解、解析 (bs4全部转换为 UTF-8 )
Beautiful Soup 是解析、遍历、维护“标签树”的功能库。
from bs4 import BeautifulSoup
import bs4
等价关系:
HTML文档 = 标签树 = BeautifulSoup类
可以将BeautifulSoup类当做对应一个HTML/XML文档的全部。
from bs4 import BeautifulSoup
soup = BeautifulSoup("<html>data</html>", "html.parser")
soup2 = BeautifulSoup(open("D://demo.html"), "html.parser")
BeautifulSoup库的解析器:
解析器
|
使用方法
|
条件
|
bs4的HTML解析器
|
BeautifulSoup(mk, "html.parser")
|
安装bs4库
|
lxml的HTML解析器
|
BeautifulSoup(mk, "lxml")
|
pip install lxml
|
lxml的XML解析器
|
BeautifulSoup(mk, "xml")
|
pip install lxml
|
html5lib的解析器
|
BeautifulSoup(mk, "html5lib")
|
pip install html5lib
|
BeautifulSoup 类的基本元素
Tag
|
标签,最基本的信息组织单元,分别用<>和</>标明开头和结尾
|
Name
|
标签名:<name>...</name>,格式:<tag>.name
|
Attributes
|
标签属性,字典的形式,格式:<tag>.attrs
|
NavigableString
|
标签内非属性字符串,<tag>.string
|
Comment
|
标签内字符串的注释部分,一种特殊的Comment类型"<b><!--This is a comment--></b>
|
IDLE演示:
>>> import requests
>>> r = requests.get("http://python123.io/ws/demo.html")
>>> demo = r.text
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(demo, "html.parser")
>>> soup.title
<title>This is a python demo page</title>
>>> soup.a
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
>>> soup.a.name
>>> soup.a.parent.name
'p'
>>> soup.a.parent.parent.name
'body'
>>> tag = soup.a
>>> tag.attrs
{'class': ['py1'], 'href': 'http://www.icourse163.org/course/BIT-268001', 'id': 'link1'}
>>> tag.attrs['class']
['py1']
>>> tag.attrs['href']
'http://www.icourse163.org/course/BIT-268001'
>>> type(tag.attrs)
<class 'dict'>
>>> type(tag)
<class 'bs4.element.Tag'>
>>> soup.a.string
'Basic Python'
>>> soup.p.string
'The demo python introduces several python courses.'
>>> type(soup.p.string)
<class 'bs4.element.NavigableString'>
三、BeautifulSoup的遍历
1、标签树的下行遍历
.contents
|
子节点的列表,将<tag>所有儿子节点存入列表
|
.children
|
子节点的迭代类型,作用同上,只能用在for...in的结构中。
|
.descendants
|
子孙节点的迭代类型,包含所有子孙节点,只能用在for...in的结构中 。
|
soup = BeautifulSoup(demo, 'html.parser')
soup.body.contents
fon child in soup.body.children:
print(child)
2、标签树的上行遍历
.parent
|
节点的父亲标签
|
.parents
|
节点先辈标签的迭代类型,只能用在for...in的结构中
|
soup = BeautifulSoup(demo, 'html.parser')
for parent in soup.a.parents:
if parent is None: #soup.parent.name == None
print(parent)
else:
print(parent.name)
3、标签树的平行遍历(所有平行遍历都在同一个父亲节点下,存在NevigableString类型)
.next_sibling
|
.previous_sibling (迭代类型,只能用在for...in的结构中)
|
.next_siblings
|
.previous_siblings (迭代类型,只能用在for...in的结构中 )
|
for sibling in soup.a.next_siblings:
print(sibling)
for sibling in soup.a.previous_siblings:
print(sibling)
四、其他方法
1、bs4 库的prettify()函数:
显示更漂亮(增加换行符)
soup = BeautifulSoup(demo, 'html.parser')
soup.prettify()
soup.a.prettify()
Unit2 : 信息的 组织 与 提取
1、信息的标记
HTML :Hyper text makeup luaguage
信息的关系
信息的标记de 三种形式:
XML: eXtensible Makeup Language
<name> ... </name>
<name / >
<!-- -->
JSON: JavaScript Object Notation (有数据类型的键值对 key : value)
“key":“value”
"key":["value1" , "value2"]
"key" : { "subkey" : "subvalue"}
“name” : [“北京理工大学”,“北京大学”]
多值用[ , ]组织
可以嵌套使用 { , }:"name":{
"newname" : "北京理工大学",
"oldName" : "延安自然研究院"
}
可以直接作为程序的一部分
YAML: YAML Ain't Markup Lauguage (无类型的键值对)
key : value
key : #Comment
-value
-value
key :
subkey : subvalue
name : 北京理工大学
缩进方式表达所属关系:
name:
newname:北京理工大学
oldname:延安自然研究院
- 表达并列关系:
name:
-北京理工大学
-延安自然研究院
| 表达整块数据 #表示注释 :
text: | #介绍
****¥%#*****123******#@¥¥@
总结:
XML :Internet 上的信息交互与传递(HTML是一种XML类)
JSON : 移动应用云端和节点的信息通信,无注释(程序对接口处理的地方)
YAML:各类系统的配置文件中,有注释易读,利用率高
2、信息的提取
方法一:完整解析信息的标记形式,再提取关键信息,形式解析
需要标记解析器 如:bs4库的标签树遍历
优点:解析准确
缺点:繁琐且慢
方法二:无视标记形式,直接搜索关键信息,搜索方法
搜索:利用查找函数即可
优点:简洁且快
缺点:确度不定,与内容有关
实际中:二者融合
实例一:提取HTML中所有的URL链接
from bs4 import BeautifulSoup
soup = BeautiflulSoup(demo, "html.parser")
for link in soup.find_all('a'):
print(link.get('href'))
<>.find_all (name, attrs, recursive, string, ##kwargs)
返回一个列表类型,储存查找的结果
简短形式:<tag>(...) 等价于 <tag>.find_all(..)
soup(...) 等价于 soup.find_all(..)
name:
soup.find_all('a')
soup.find_all(['a','b'])
for tag in soup.find_all(True):
print(tag.name)
import re
for tag in soup.find_all(re.compile('b')): #所有以b开头的标签
print(tag.name)
attrs:
soup.find_all('p', 'course') #查找页面中所有属性值为字符串'course'的p标签
soup.find_all(id='link1') # 对属性进行查找的时候必须精确的复制这个信息
import re
soup.find_all(id=re.compile('link'))
recursive:是否对子孙全部检索,默认True, Bool值
soup.find_all('a', recursive = False) #只查找当前节点的儿子节点
string:<>...</>对标签中的字符串域进行检索
soup.find_all(string = 'Basic Python')
import re
soup.find_all(string = re.compile('Python'))
find_all的扩展方法:
<>.find(), <>.find_parents(), <>.find_parent(), <>.find_next_sibling(), <>find_next_siblings(), <>.find_previous_sibling(), <>.find_previous_sibllings().
Unit3 : 爬虫实例一
中国大学排名爬取
功能描述:
输入:大学排名URL链接
输出:大学排名信息的屏幕输出(排名,大学名称,总分)
技术路线:requests-bs4
定向爬虫:仅对输入URL进行爬取,不扩展爬取。
静态、定向
步骤一:从网络上获取大学排名网页内容
getHTMLText()
步骤二:提取网页内容的信息到合适的数据结构中
fillUnivList()
步骤三:利用数据结构展示并输出结果
printUnivList()
程序的结构设计:二维列表
import requests
from bs4 import BeautifulSoup
import bs4
def getHTMLText(url):
try:
r = requests.get(url, timeout = 20)
r.encoding = r.apparent_encoding
return r.text
except:
return ""
def fillUnivList(ulist, html):
soup = BeautifulSoup(html, "html.parser")
for tr in soup.find('tbody').children:
if isinstance(tr, bs4.element.Tag): #排除其中的string类型
tds = tr('td')
ulist.append([tds[0].string, tds[1].string,tds[3].string])
def printUnivList(ulist, num): #需要格式化输出: "{}{}" .format()
tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"
print(tplt.format("排名","学校名称","总分", chr(12288))) #解决中文输出排版的问题
for i in range(num):
u = ulist[i]
print(tplt.format(u[0],u[1],u[2], chr(12288)))
def main():
uinfo = []
url = "http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html"
html = getHTMLText(url)
fillUnivList(uinfo, html)
printUnivList(uinfo, 20) #20 univs
main()
优化:
1、中文对齐问题
format()函数:
'{0}' ' {0[1]}{1[0]} ' '{:<>^8}' '{ : .f}' '{ : b c d o x X}'
因为位置填充采用的是西文字符空格填充,所以中文对齐会不理想。
从而,采用中文字符的空格填充chr(12288)
tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"
print(tplt.format("排名","学校名称","总分", chr(12288)))
网络爬虫系列笔记(3)——Beautiful Soup库相关推荐
- Python 网络爬虫笔记5 -- Beautiful Soup库实战
Python 网络爬虫笔记5 – Beautiful Soup库实战 Python 网络爬虫系列笔记是笔者在学习嵩天老师的<Python网络爬虫与信息提取>课程及笔者实践网络爬虫的笔记. ...
- Python 网络爬虫笔记3 -- Beautiful Soup库
Python 网络爬虫笔记3 – Beautiful Soup库 Python 网络爬虫系列笔记是笔者在学习嵩天老师的<Python网络爬虫与信息提取>课程及笔者实践网络爬虫的笔记. 课程 ...
- 爬虫第二讲:Beautiful Soup库
第二讲 Beautiful Soup库 一.Beautiful Soup库基础 1.示例引入 #首先爬取下页面 >>>import requests >>>r = ...
- Python网络爬虫:基础知识Beautiful Soup
一.Beautiful Soup简介 网络数据挖掘指的是从网站中获取数据的过程,数据挖掘技术可以让我们从网站世界中收集大量有价值的数据. Beautiful Soup是一个Python库,可以从HTM ...
- python网络爬虫系列教程——python中pyquery库应用全解
全栈工程师开发手册 (作者:栾鹏) python教程全解 python网络爬虫lxml库的应用全解. 在线安装方法:cmd中输入"pip install pyquery" 离线安装 ...
- python网络爬虫系列教程——python中lxml库应用全解(xpath表达式)
全栈工程师开发手册 (作者:栾鹏) python教程全解 python网络爬虫lxml库的应用全解. 在线安装方法:cmd中输入"pip install lxml" 离线安装,下载 ...
- python网络爬虫系列教程——python中requests库应用全解
全栈工程师开发手册 (作者:栾鹏) python教程全解 python中requests库的基础应用,网页数据挖掘的常用库之一.也就是说最主要的功能是从网页抓取数据. 使用前需要先联网安装reques ...
- python网络爬虫系列(一)——urllib库(urlopen、urlretrieve、urlencode、parse-qs、urlparse和urlsplit、request.Request类)
urllib库 urllib库是Python中一个最基本的网络请求库.可以模拟浏览器的行为,向指定的服务器发送一个请求,并可以保存服务器返回的数据. 一.urlopen函数: 在Python3的url ...
- python网络爬虫——自学笔记1.用requests库爬取图片
1.requests库的安装 rrequests库是公认的python的一个一个非常优秀的第三方库,下载方法也很简单 只需Win+R打开控制台命令窗口,输入pip install requests后回 ...
最新文章
- 图解深度学习(图灵出品)
- rtems线程管理与调度(一)
- Java中long和Long有什么区别
- ps意外崩溃_充满意外的数学中考
- Python常见的数据类型【数字、布尔、字符串、列表和元组、字典】
- C++学习之路(一)
- 并发量,QPS,TPS,看这一篇就够了
- RabbitAdmin 实战
- springcloud 使用git作为配置中心
- JS学习笔记(不断更新)
- android 动态申请camera权限,GitHub - yinzhengwei/permissiongranted: Android动态权限检测和申请管理...
- 构建一个pool来管理无刷新页面的xmlhttp对象
- vue中el-calendar自定义日历控件
- 《C》C语言编程实现指定阶“m序列”并通过gnuplot绘图
- java解析数据_java解析txt里的数据
- 地球人都在玩跨境电商
- 汽车研发的五大阶段及制造的四大工艺
- 怎么判断电脑是32位还是64位呢
- MTK6735 android开发记录 编译配置(一)
- (五)Richardson 迭代法
热门文章
- 苹果cmsV10-Dplayer播放器插件整合前置广告、暂停广告
- 关于数字化运营,你想了解的都在这里
- win ssh key多账号配置
- 骆驼命名法——C++实现
- 一文搞定ClickHouse在苏宁用户画像场景的实践(建议收藏)
- Dram学习笔记(2) 读《终极内存技术指南》笔记 + 纠正一些流传很广的文章错误
- (C语言)常用的字符串函数介绍(strcpy,strncpy,strcat,strncat,strcmp,strncmp,strchar,strlen)非常详细
- 戴尔从固态硬盘启动系统
- html加百度链接地址,如何给百度影音地址添加超链接网址
- 魅族是否参与了鸿蒙,魅族宣布接入鸿蒙