Beautiful Soup库安装

pip install beautifulsoup4

测试:

import requests r = requests.get("http://python123.io/ws/demo.HTML") demo = r.text form bs4 import BeautifulSoup #从bs4中引入BeautifulSoup类 soup = BeautifulSoup(demo, "html.parser")

python网络爬虫步骤(Python网络爬虫BeautifulSoup库入门)(1)

Beautiful Soup库是解析、遍历、维护“标签树”的功能库

Beautiful Soup库的基本元素

Beautiful Soup库的引用

Beautiful Soup库,也叫beautifulsoup4或bs4.

from bs4 import BeautifulSoup soup = BeautifulSoup(demo,"html.parser")

Beautiful Soup类的基本元素

python网络爬虫步骤(Python网络爬虫BeautifulSoup库入门)(2)

基于bs4库的HTML内容遍历方法

下行遍历

python网络爬虫步骤(Python网络爬虫BeautifulSoup库入门)(3)

#遍历儿子节点 for child in soup.body.children print(child) #遍历子孙节点 for child in soup.body.descendants print(child)

上行遍历

python网络爬虫步骤(Python网络爬虫BeautifulSoup库入门)(4)

soup = BeautifulSoup(demo,"html.parser") for parent in soup.a.parents: if parent is None: print(parent) else: print(parent.name) #输出结果 #p #body #html #[document]

平行遍历

平行遍历发生在同一个父节点下的各节点间。

下一个获取的可能是字符串类型,不一定是下一个节点。

python网络爬虫步骤(Python网络爬虫BeautifulSoup库入门)(5)

#遍历后续节点 for sibling in soup.a.next_siblings print(sibling) #遍历前续节点 for sibling in soup.a.previous_siblings print(sibling)

基于bs4库的HTML格式化和编码

格式化方法:.prettify()

soup = BeautifulSoup(demo,"html.parser") print(soup.a.prettify())

编码:默认utf-8

soup = BeautifulSoup("<p>中文</p>","html.parser") soup.p.string #'中文' print(soup.p.prettify()) #<p> # 中文 #</p>

3.信息组织与提取

信息标记的三种形式

标记后的信息可形成信息组织结构,增加了信息的维度;

标记后的信息可用于通信、存储和展示;

标记的结构和信息一样具有重要价值;

标记后的信息有利于程序的理解和运用。

XML: eXtensible Matkup Language

最早的通用信息标记语言,可扩展性好,但繁琐。

用于Internet上的信息交互和传递。

<name>...</name> <name/> <!-- -->

JSON: JavaScript Object Notation

信息有类型,适合程序处理(js),较XML简洁。

用于移动应用云端和节点的信息通信,无注释。

#有类型的键值对表示信息的标记形式 "key":"value" "key":["value1","value2"] "key":{"subkey":"subvalue"}

YAMl: YAML Ain’t Markup Language

信息无类型,文本信息比例最高,可读性好。

用于各类系统的配置文件,有注释易读。

#无类型的键值对表示信息的标记形式 key : "value" key : #comment -value1 -value2 key : subkey : subvalue

信息提取的一般方法

方法一:完整解析信息的标记形式,再提取关键信息。

XML JSON YAML

需要标记解析器,例如bs4库的标签树遍历。

优点:信息解析准确

缺点:提取过程繁琐,过程慢

方法二:无视标记形式,直接搜索关键信息

搜索

对信息的文本查找函数即可。

优点:提取过程简洁,速度较快

缺点:提取过程准确性与信息内容相关

融合方法:结合形式解析与搜索方法,提取关键信息

XML JSON YAML 搜索

需要标记解析器及文本查找函数。

实例:提取HTML中所有URL链接

思路:

1、搜索到所有 标签

2、解析 标签格式,提取href后的链接内容

form bs4 import BeautifulSoup soup = BeautifulSoup(demo,"html.parser") for link in soup.find_all('a'): print(link.get('href'))

基于bs4库的HTML内容查找方法

python网络爬虫步骤(Python网络爬虫BeautifulSoup库入门)(6)

简写形式:

(…) 等价于

.find_all(…)

#name:对标签名称的检索字符串 soup.find_all('a') soup.find_all(['a', 'b']) soup.find_all(True) #返回soup的所有标签信息 for tag in soup.find_all(True): print(tag.name) #html head title body p b p a a #输出所有b开头的标签,包括b和body #引入正则表达式库 import re for tag in soup.find_all(re.compile('b')): print(tag.name) #body b #attrs:对标签属性值的检索字符串,可标注属性检索 soup.find_all('p', 'course') soup.find_all(id='link1') import re soup.find_all(id=re.compile('link')) #recursive:是否对子孙全部检索,默认为True soup.find_all('p', recursive = False) #string:<>...</>字符串区域的检索字符串 soup.find_all(string = "Basic Python") import re soup.find_all(string = re.compile('Python')) #简写形式:soup(..) = soup.find_all(..)

拓展方法:参数同.find_all()

python网络爬虫步骤(Python网络爬虫BeautifulSoup库入门)(7)

4.信息提取实例

中国大学排名定向爬虫

功能描述:

​ 输入:大学排名URL链接

​ 输出:大学排名信息的屏幕输出(排名,大学名称,总分)

​ 技术路线:requests-bs4

​ 定向爬虫:仅对输入URL进行爬取,不拓展爬取

程序的结构设计:

​ 步骤1:从网络上获取大学排名网页内容

​ getHTMLText()

​ 步骤2:提取网页内容中信息到合适的数据结构

​ fillUnivList()

​ 步骤3:利用数据结构展示并输出结果

​ printUnivList()

初步代码编写

import requests from bs4 import BeautifulSoup import bs4 ''' 这是小编准备的python爬虫学习资料,加群:821460695 即可免费获取! ''' def getHTMLText(url): try: r = requests.get(url, timeout= 30) r.raise_for_status() 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): tds = tr('td') ulist.append([tds[0].string, tds[1].string, tds[3].string]) def printUnivList(ulist, num): print("{:^10}\t{:^6}\t{:^10}".format("排名", "学校名称", "分数")) for i in range(num): u = ulist[i] print("{:^10}\t{:^6}\t{:^10}".format(u[0], u[1], u[2])) def main(): uinfo = [] url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html' html = getHTMLText(url) fillUnivList(uinfo,html) printUnivList(uinfo,20) #20 univs main()

中文输出对齐问题

当输出中文的宽度不够时,系统会采用西文字符填充,导致对齐出现问题。

可以使用中文空格chr(12288)填充解决。

<填充> :用于填充的单个字符

<对齐> :<左对齐 >右对齐 ^居中对齐

<宽度> :槽的设定输出宽度

, :数字的千位分隔符适用于整数和浮点数

<精度> :浮点数小数部分的精度或字符串的最大输出长度

<类型> :整数类型b,c,d,o,x,X浮点数类型e,E,f,%

代码优化

import requests from bs4 import BeautifulSoup import bs4 ''' 这是小编准备的python爬虫学习资料,加群:821460695 即可免费获取! ''' def getHTMLText(url): try: r = requests.get(url, timeout= 30) r.raise_for_status() 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): tds = tr('td') ulist.append([tds[0].string, tds[1].string, tds[3].string]) def printUnivList(ulist, num): 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()

,