https://cuiqingcai.com/5548.html
https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/#name
Table of Contents
prettify()方法。这个方法可以把要解析的字符串以标准的缩进格式输出
string 或 get_text() 属性就可以得到标签里面的文本
from bs4 import BeautifulSoup
soup = BeautifulSoup('<p>Hello</p>', 'lxml')
print(soup.p.string)
基本使用
prettify()
方法。这个方法可以把要解析的字符串以标准的缩进格式输出
string 或 get_text()
属性就可以得到标签里面的文本
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
# 补全 html 标签
print(soup)
# 按标准的缩进格式输出
print(soup.prettify())
print(soup.title.string)
节点选择器
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
# 打印输出title节点的选择结果
print(soup.title)
# 类型 <class 'bs4.element.Tag'>
print(type(soup.title))
# 打印输出title节点 的 文本
print(soup.title.string)
# 打印输出 head 节点
print(soup.head)
# 打印输出 p 节点
print(soup.p)
获取名称
name
属性获取节点的名称
print(soup.title.name)
# title
获取属性
每个节点可能有多个属性,比如id
和class
等,选择这个节点元素后,可以调用 attrs
获取所有属性
可以看到,attrs
的返回结果是字典形式,它把选择的节点的所有属性和属性值组合成一个字典。接下来,如果要获取name
属性,就相当于从字典中获取某个键值,只需要用中括号加属性名就可以了。比如,要获取name
属性,就可以通过attrs['name']
来得到。
print(soup.p.attrs)
print(soup.p.attrs['name'])
# {'class': ['title'], 'name': 'dromouse'}
# dromouse
其实这样有点烦琐,还有一种更简单的获取方式:可以不用写attrs
,直接在节点元素后面加中括号,传入属性名就可以获取属性值了。样例如下:
print(soup.p['name'])
print(soup.p['class'])
# dromouse
# ['title']
嵌套选择
html = """
<html><head><title>The Dormouse's story</title></head>
<body>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(soup.head.title)
print(type(soup.head.title))
print(soup.head.title.string)
# <title>The Dormouse's story</title>
# <class 'bs4.element.Tag'>
# The Dormouse's story
关联选择
(1)子节点和子孙节点
contents 和
children 属性得到的结果是直接子节点的列表
descendants
属性得到所有的子孙节点的话
html = """
<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
<p class="story">
Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">
<span>Elsie</span>
</a>
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a>
and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>
and they lived at the bottom of a well.
</p>
<p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(soup.p.children)
# 子节点
for i, child in enumerate(soup.p.children):
print(i, child)
# 子节点
for i, child in enumerate(soup.p.contents):
print(i, child)
# 子孙节点
for i, child in enumerate(soup.p.descendants):
print(i, child)
(2)父节点和祖先节点
如果要获取某个节点元素的父节点,可以调用 parent
属性
如果想获取所有的祖先节点,可以调用 parents
属性
html = """
<html>
<body>
<p class="story">
<a href="http://example.com/elsie" class="sister" id="link1">
<span>Elsie</span>
</a>
</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(type(soup.a.parents))
# 父节点
print(soup.a.parent)
print('*'*20)
# 祖先节点
print(list(enumerate(soup.a.parents)))
(3)兄弟节点
next_sibling
和 previous_sibling
分别获取节点的下一个和上一个兄弟元素
next_siblings
和 previous_siblings
则分别返回所有前面和后面的兄弟节点的生成器
html = """
<html>
<body>
<p class="story">
Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">
<span>Elsie</span>
</a>
Hello
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a>
and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>
and they lived at the bottom of a well.
</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print('Next Sibling', soup.a.next_sibling)
print('Prev Sibling', soup.a.previous_sibling)
print('Next Siblings', list(enumerate(soup.a.next_siblings)))
print('Prev Siblings', list(enumerate(soup.a.previous_siblings)))
(4)提取信息
html = """
<html>
<body>
<p class="story">
Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Bob</a><a href="http://example.com/lacie" class="sister" id="link2">Lacie</a>
</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(soup.a.next_sibling)
print(soup.a.next_sibling.string)
print(list(soup.a.parents)[0])
print(list(soup.a.parents)[0].attrs['class'])
方法选择器
find_all()
查询所有符合条件的元素
1. name 节点名查询
find_all(name , attrs , recursive , text , **kwargs)
html='''
<div class="panel">
<div class="panel-heading">
<h4>Hello</h4>
</div>
<div class="panel-body">
<ul class="list" id="list-1">
<li class="element">Foo</li>
<li class="element">Bar</li>
<li class="element">Jay</li>
</ul>
<ul class="list list-small" id="list-2">
<li class="element">Foo</li>
<li class="element">Bar</li>
</ul>
</div>
</div>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
# 节点名查询
print(soup.find_all(name='ul'))
print('*'*20)
print(soup.find_all(name='ul')[0])
2. attrs 属性查询
html='''
<div class="panel">
<div class="panel-heading">
<h4>Hello</h4>
</div>
<div class="panel-body">
<ul class="list" id="list-1" name="elements">
<li class="element">Foo</li>
<li class="element">Bar</li>
<li class="element">Jay</li>
</ul>
<ul class="list list-small" id="list-2">
<li class="element">Foo</li>
<li class="element">Bar</li>
</ul>
</div>
</div>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(soup.find_all(attrs={'id': 'list-1'}))
print(soup.find_all(attrs={'name': 'elements'}))
3. text 是正则 返回的是内容没有标签
import re
html='''
<div class="panel">
<div class="panel-heading">
<h4>Hello</h4>
</div>
<div class="panel-body">
<ul class="list" id="list-1" name="elements">
<li class="element">Foo</li>
<li class="element">Bar</li>
<li class="element">Jay</li>
</ul>
<ul class="list list-small" id="list-2">
<li class="element">Foo</li>
<li class="element">Bar</li>
</ul>
</div>
</div>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(soup.find_all(text=re.compile('Foo')))
print(soup.find_all(text=re.compile('He')))
# ['Foo', 'Foo']
# ['Hello']
find() 返回单个元素 , 匹配的第一个元素
css 选择器
. 点 class
# 井号 id
html='''
<div class="panel">
<div class="panel-heading">
<h4>Hello</h4>
</div>
<div class="panel-body">
<ul class="list" id="list-1" name="elements">
<li class="element">Foo</li>
<li class="element">Bar</li>
<li class="element">Jay</li>
</ul>
<ul class="list list-small" id="list-2">
<li class="element">Foo</li>
<li class="element">Bar</li>
</ul>
</div>
</div>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
print(soup.select('.panel-body li'))
print(soup.select('.panel-body #list-2 li'))
print(soup.select('#list-1 li'))
select 选择获取属性的内容
import requests
from bs4 import BeautifulSoup
import jsonpath
def handler_info(url):
js = {
"dzwww.com": {
"titlelevel": 0,
"titlerule": ["#xl-headline > div > h2","div#headline>h1","div#wrapper>h1","div.txt>h2","div.layout > h2"],
"authorrule": "div.layout >div.left",
"authorlevel": 0,
"pubdaterule": ["#xl-headline > div > div.left","div#headline>i","div.txt>p","div.layout >div.left"],
"contentrule": ["div.news-con","div.photoNews", "div.con > div"],
"contentlevel": 0,
"pubdatelevel": 0
}
}
title = jsonpath.jsonpath(js,'$..titlerule')[0]
zuozhe = jsonpath.jsonpath(js,'$..pubdaterule')[0]
content = jsonpath.jsonpath(js,'$..contentrule')[0]
html = requests.get(url)
html.encoding = 'gb2312'
# print(html.text)
soup = BeautifulSoup(html.text,'lxml')
bt = soup.select_one(title[0]).text
zz = soup.select_one(zuozhe[0]).text
nr = soup.select_one(content[0]).text
print(bt)
print(zz)
print(nr)
url = 'http://culture.dzwww.com/wx/201902/t20190228_18442637.htm'
handler_info(url)
或者
bt = soup.select(title[0])[0].text
zz = soup.select(zuozhe[0])[0].text
nr = soup.select(content[0])[0].text