网络爬虫系列笔记(3)——Beautiful Soup库
来源:互联网 发布:骑士团国家知乎 编辑:程序博客网 时间:2024/06/05 07:27
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库的解析器:
BeautifulSoup 类的基本元素
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、标签树的下行遍历
soup = BeautifulSoup(demo, 'html.parser')
soup.body.contents
fon child in soup.body.children:
print(child)
2、标签树的上行遍历
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类型)
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)))
阅读全文
0 0
- 网络爬虫系列笔记(3)——Beautiful Soup库
- Python网络爬虫——Beautiful Soup库
- python网络爬虫基础(2)--Beautiful Soup库
- 爬虫---Beautiful Soup库
- Python爬虫学习二——Beautiful Soup库
- Python网络爬虫与信息提取-Day6-Beautiful Soup库
- python 网络爬虫 Beautiful Soup用法
- python爬虫-Beautiful Soup学习笔记
- python——爬虫学习——Beautiful Soup库的使用-(2)
- HDU4782——Beautiful Soup(模拟)
- 【Python】【爬虫】关于Beautiful Soup库
- 爬虫:Beautiful Soup
- Beautiful Soup写爬虫
- Learn Beautiful Soup(3)——使用Beautiful Soup进行查找
- Learn Beautiful Soup(3)——使用Beautiful Soup进行查找
- 【Python网络爬虫开发教程】Beautiful Soup 4.2.0 文档
- Python3网络爬虫(七):使用Beautiful Soup爬取小说
- Python3网络爬虫(二):使用Beautiful Soup爬取小说
- 有关WSGi的认识和讨论
- 人脸识别教程【Windows】
- Android TV开发总结(一)
- MyEclipse改字体
- x-pack安装结合elasticsearch5.4和kibana5.4
- 网络爬虫系列笔记(3)——Beautiful Soup库
- linux中软链接和硬链接的区别与小结
- 《leetcode》search-insert-position
- Java并行程序设计模式小结
- echarts页面的图表的base64生成图片折线图只有点
- 使用Nginx反向代理和内容替换模块实现网页内容动态替换功能
- 使用Apriori进行关联分析(二)
- 腾讯云 基于 CentOS 搭建 Discuz 论坛
- POJ