bs4(BeautifulSoup)库的基本使用
1.导入模块
from bs4 import BeautifulSoup
2.解析获取到的网页内容
文档被转换成Unicode,并且HTML的实例都被转换成Unicode编码。
可以打印soup对象的内容,格式化输出:print soup.prettify()
url_str = getHTMLText(url)
soup = BeautifulSoup(url_str,'html.parser')
3.基本使用方法
bs4 将复杂的HTML文档转换成一个复杂的树形结构,每个节点都是python的对象。
根据标签查找(type:bs4_obj)
head = soup.head
"""
<head>
<meta content="text/html;charset=utf-8" http-equiv="content-type"/>
<meta content="IE=Edge" http-equiv="X-UA-Compatible"/>
<meta content="always" name="referrer"/>
<link href="http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css" rel="stylesheet" type="text/css"/>
<title>
百度一下,你就知道
</title>
</head>
"""
获取属性
title = head.title # 在soup中获取第一个符合要求的标记
# <title>百度一下,你就知道</title>
title_str = name.string # 获取标签内部的文字
# 百度一下,你就知道
meta = head.meta
# <meta content="text/html;charset=utf-8" http-equiv="content-type"/>
content = meta.get('content') # 获取meta中第一个属性
content = meta['content']
# text/html;charset=utf-8
content = meta.attrs # 获取meta中所有属性
# {'http-equiv': 'content-type', 'content': 'text/html;charset=utf-8'}
meta.name = 'hi' # 修改标签的name
meta['content'] = 'hello world' # 修改标签的属性和内容
print(meta)
# <hi content="hello world" http-equiv="content-type"/>
获取文本内容
content = head.contents # 返回以head下各标签为元素的列表
"""
[<meta content="text/html;charset=utf-8" http-equiv="content-type"/>, <meta content="IE=Edge" http-equiv="X-UA-Compatible"/>, <meta content="always" name="referrer"/>, <link href="http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css" rel="stylesheet" type="text/css"/>, <title>百度一下,你就知道</title>]
"""
print(content[0])
# <meta content="text/html;charset=utf-8" http-equiv="content-type"/>
text = head.get_text() # 获取head标签内部的文字
# 百度一下,你就知道
print(type(head.title.string)) # bs4.element.NavigableString
if type(head.title.string)== bs4.element.NavigableString: # 过滤注释内容
print('这是注释内容')
else:
print('这不是注释')
获取子孙节点(tpye:generator)
descendants = soup.p.descendants
find&&find_all查找
find_all( name , attrs , recursive , text , **kwargs )
soup.find('a')
soup.find('a',title='hhh')
soup.find('a',id='',class_='')
soup.find_all('a') # 查找所有<a>标签
soup.find(id=True) # 查找所有包含id属性的标签
soup.find_all(limit=2) # 限定查找的返回数量
soup.find_all(['a','p']) # 查找所有<a>标签和<b>标签
str(soup.find_all('a',class_='title')[0]) # 注意因为class为关键字,所以用'class_'代替
soup.find_all(attrs = {'data-role':'goto-input'}) # '-'不能直接用作属性名,需用字典括起来
select选择(type:list)
soup.select('.main > ul > li > a')[0].string