Python爬虫入门-3.Beautiful Soup库入门

1. 安装

cmd命令行下,BeautifulSoup的安装:

pip3 install beautifulsoup4

使用下面的网站进行测试:

import requests
vUrl = requests.get("http://python123.io/ws/demo.html")
vUrl.text
'<html><head><title>This is a python demo page</title></head>\r\n<body>\r\n<p class="title"><b>The demo python introduces several python courses.</b></p>\r\n<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n<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>\r\n</body></html>'
import requests
from bs4 import BeautifulSoup
vUrl = requests.get("http://python123.io/ws/demo.html")
vDemo = vUrl.text
vSoup = BeautifulSoup(vDemo, "html.parser")
print(vSoup.prettify())
<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 class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">
    Basic Python
   </a>
   and
   <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">
    Advanced Python
   </a>
   .
  </p>
 </body>
</html>

2.Beautifulsoup的元素

  • Beautiful Soup库解析器:
解析器 使用方法 条件
bs4的HTML解析器 BeautifulSoup(data, "html.parser") 安装bs4库
lxml的HTML解析器 BeautifulSoup(data, "lxml") pip3 install lxml
lxml的XML解析器 BeautifulSoup(data, "xml") pip3 install lxml
html5lib的解析器 BeautifulSoup(data, "html5lib") pip3 install html5
  • Beautiful Soup类的基本元素
基本元素 说明
Tag 标签,最基本的单元组织,分别用<>和</>标明开头和结尾
Name 标签的名字,<p>...</p>,的名字是"p",格式:<tag>.name
Attributes 标签的属性,字典形式组织,格式:<tag>.attrs
NavigableString 标签内非属性字符串,<>...</>中文字符,格式:<tag>.string
Comment 标签内字符串的注释部分,一种特殊的Comment类型
import requests
from bs4 import BeautifulSoup
vUrl = requests.get("http://python123.io/ws/demo.html")
vDemo = vUrl.text
vSoup = BeautifulSoup(vDemo, "html.parser")
vSoup.title # 返回title标签
vTag = vSoup.a # 将a标签存进一个变量中
print(vTag.name) # 返回a的名字
print(vSoup.a.parent.name) # 等同于vTag.parent.name 父结构的名字
print(vSoup.a.parent.parent.name)
print(vTag.attrs) # 获得字典格式的属性内容
print(vTag.attrs["class"]) # 查看class属性
print(vTag.attrs["href"]) # 查看href属性
print(type(vTag.attrs)) # 查看类型
print(type(vTag)) # 查看类型
print(vTag.string)
a
p
body
{'href': 'http://www.icourse163.org/course/BIT-268001', 'class': ['py1'], 'id': 'link1'}
['py1']
http://www.icourse163.org/course/BIT-268001
<class 'dict'>
<class 'bs4.element.Tag'>
Basic Python

3. Beautiful Soup元素的遍历

分为下行遍历、上行遍历以及平行遍历。

  • 下行遍历
属性 说明 数据类型
.contents 子节点的列表,将<tag>所有子节点存入列表 列表
.children 子节点的迭代类型,与.contents类似,用于循环遍历子节点 迭代类型
.descendants 子孙节点的跌点类型,包含所有子孙节点,用于遍历循环 迭代类型
import requests
from bs4 import BeautifulSoup
vUrl = requests.get("http://python123.io/ws/demo.html")
vDemo = vUrl.text
vSoup = BeautifulSoup(vDemo, "html.parser")
print(vSoup.head)
print(vSoup.head.contents)
<head><title>This is a python demo page</title></head>
[<title>This is a python demo page</title>]
print(vSoup.body.contents)
['\n', <p class="title"><b>The demo python introduces several python courses.</b></p>, '\n', <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 class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p>, '\n']
len(vSoup.body.contents)
5
vSoup.body.contents[1]
<p class="title"><b>The demo python introduces several python courses.</b></p>
vSoup.body.contents[2]
'\n'
vSoup.body.contents[3]
<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 class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p>

标签树的下行遍历代码:

### 遍历子节点
for vChild in vSoup.body.children:
    print(vChild)
### 遍历子孙节点
for vChild in vSoup.body.children:
    print(vChild)
  • 上行遍历
属性 说明
.parent 节点的父亲标签
.parents 节点的先辈标签
import requests
from bs4 import BeautifulSoup
vUrl = requests.get("http://python123.io/ws/demo.html")
vDemo = vUrl.text
vSoup = BeautifulSoup(vDemo, "html.parser")
vSoup.title.parent # tltle的父标签是head
<head><title>This is a python demo page</title></head>
vSoup.html.parent # 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 class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> and <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>.</p>
</body></html>
vSoup.parent # vSoup是特殊对象,其父标签为空
### 查看上行标签的名字
import requests
from bs4 import BeautifulSoup
vUrl = requests.get("http://python123.io/ws/demo.html")
vDemo = vUrl.text
vSoup = BeautifulSoup(vDemo, "html.parser")
for parent in vSoup.a.parents:
    if parent is None:
        print(parent)
    else:
        print(parent.name)
p
body
html
[document]
  • 平行遍历
属性 说明 数据类型
.next_sibling 返回按照html文本顺序的下一个平行节点标签 list
.previous_sibling 返回按照html文本顺序的上一个平行节点的标签 list
.next_siblings 迭代类型,返回按照html文本顺序的后续所有平行节点标签 迭代类型
.previous_siblings 迭代类型,返回按照html文本顺序的前序所有平行节点标签 迭代类型

平行遍历必须发生在同一个父节点下。

import requests
from bs4 import BeautifulSoup
vUrl = requests.get("http://python123.io/ws/demo.html")
vDemo = vUrl.text
vSoup = BeautifulSoup(vDemo, "html.parser")
vSoup.a.next_sibling # 忘后一个平行节点是一个字符串
' and '
vSoup.a.next_sibling.next_sibling #往后两个平行节点也是一个a标签
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>
vSoup.a.previous_sibling # 前一个平行节点是一段文字
'Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n'
vSoup.a.previous_sibling.previous_sibling # 前一个的前一个不存在,所以没有输出

标签数的平行遍历:

for vSibling in vSoup.a.next_siblings:
    print(vSibling)
 and 
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>
.
for vSibling in vSoup.a.previous_siblings:
    print(vSibling)
Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,589评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,615评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,933评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,976评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,999评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,775评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,474评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,359评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,854评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,007评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,146评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,826评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,484评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,029评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,153评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,420评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,107评论 2 356

推荐阅读更多精彩内容