之前我爬取得到的页面都是HTML文档,阅读起来不是很友好,我们可以使用 bs4
库的BeautifulSoup模块来解析HTML,分析提取其中的内容。
step1:打开cmd
step2:输入下面命令安装bs4
pip install bs4
我们首先需要制作soup,再通过soup完成各种操作: data
语法:
from bs4 import BeautifulSoup
soup = BeautifulSoup(
创建对象:创建BeautifulSoup类的对象:
from bs4 import BeautifulSoup
soup1 = BeautifulSoup("This is content
", "html.parser")
soup2 = BeautifulSoup(open("D://demo.html"), "html.parser")
使用举例:我们可以调用BeautifulSoup类对象的prettify来格式化HTML代码
import requests
from bs4 import BeautifulSoup
soup = BeautifulSoup("中文
", "html.parser")
print(soup.prettify())
美化后的HTML代码:
<p>
中文
</p>
基本元素 | 说明 |
---|---|
Tag | 标签,最基本的信息组织单元,分别用<>he >标明开否和结尾 |
Name | 标签的名字,如 data 的名字为‘p’,格式: |
Attributes | 标签的属性,字典组织形式,格式: |
Navigable String | 标签内非属性的字符串,格式: |
Comment | 标签内字符串的注释部分 |
使用举例:
import requests
from bs4 import BeautifulSoup
url = "http://python123.io/ws/demo.html"
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")
使用 tag
元素:
>>> print(soup.title)
<title>This is a python demo page</title>
>>> print(soup.a)
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
>>> print(type(soup.a))
<class 'bs4.element.Tag'>
使用 name
元素
>>> print(soup.a.name)
a
>>> print(soup.a.parent.name)
p
使用 Attributes
属性
>>> print(soup.a.attrs)
{
'href': 'http://www.icourse163.org/course/BIT-268001', 'class': ['py1'], 'id': 'link1'}
>>> print(soup.a.attrs["class"])
['py1']
使用 Navigable String
属性
>>> print(soup.a.string)
Basic Python
>>> print(soup.p.string)
The demo python introduces several python courses.
HTML基本格式:
标签树的下行遍历:
1、下行遍历属性:
属性 | 说明 |
---|---|
.contents | 子节点的列表,将 |
.children | 子节点的迭代类型,与 .content 类似,用于循环遍历儿子节点 |
.descendants | 子孙结点的迭代类型,包含所有的子孙节点,用于循环遍历 |
2、遍历框架
for child in soup.body.children: # 遍历儿子节点
print(child)
for child in soup.body.descendants: # 遍历子孙节点
print(child)
3、例子
import requests
from bs4 import BeautifulSoup
url = "http://python123.io/ws/demo.html"
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")
print(soup.head.contents)
print(len(soup.body.contents))
print(soup.body.contents)
print(soup.body.contents[1])
标签树的上行遍历:
1、上行遍历属性:
属性 | 说明 |
---|---|
.parent | 节点的父亲标签 |
.parents | 节点的先辈标签的迭代类型,用于循环遍历先辈节点 |
2、例子
在这里插入代码片import requests
from bs4 import BeautifulSoup
url = "http://python123.io/ws/demo.html"
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")
print(soup.parent)
for parent in soup.a.parents:
if parent is None:
print(parent)
else:
print(parent.name)
输出:
None
p
body
html
[document]
***Repl Closed***
注意,soup没有parent,返回输出一个空列表
标签树的平行遍历:
1、平行遍历属性:
属性 | 说明 |
---|---|
.next_sibling | 前兄弟节点标签 |
.previous_sibling | 后兄弟节点标签 |
.next_siblings | 前兄弟节点标签可迭代类型,用于循环遍历 |
.previous_siblings | 后兄弟节点标签可迭代类型,用于循环遍历 |
2、例子
import requests
from bs4 import BeautifulSoup
url = "http://python123.io/ws/demo.html"
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")
for sibling in soup.a.next_siblings:
print(sibling.name)
输出:
None
a
None
第四篇python爬虫学习笔记完结啦 cheers ??