学习Python的第二天之网络爬虫
30岁程序员学习Python的第二天之网络爬虫的信息提取
BeautifulSoup库
地址:https://beautifulsoup.readthedocs.io/zh-cn/v4.4.0/
1、BeautifulSoup4安装
在windows系统下通过管理员权限运行cmd窗口
运行pip install beautifulsoup4
测试实例
import requests
from bs4 import BeautifulSoup
r = requests.get('https://python123.io/ws/demo.html')
print(r.text)
demo = r.text
soup = BeautifulSoup(demo, 'html.parser')
print(soup.prettify())
注:prettify() 方法将Beautiful Soup的文档树格式化后以Unicode编码输出,每个XML/HTML标签都独占一行
2、BeautifulSoup库基本信息
Beautiful Soup库是解析、遍历、维护“标签树”的功能库
BeautifulSoup库是标签Tag进行解析的。
例:<p calss=“title”> … </p> 每个标签都是成对出现的,并且在第一个标签上可以有多个属性值
可通过以下语句导入beautiful Soup库
from bs4 import BeautifulSoup
或
import bs4
BeautifulSoup的解析器
BeautifulSoup类的基本元素
如何通过解析获取每个标签内容
1、获取Tag的名字:<tag>.name
soup = BeautifulSoup(demo, 'html.parser')
print(soup.title.name)
2、获取Tag的attrs(属性):<tag>.attrs
soup = BeautifulSoup(demo, 'html.parser')
print(soup.a.attrs)
print(soup.a['href'])
print(soup.a['id'])
3、获取Tag内的NavigableString(非属性字符串):<tag>.string
soup = BeautifulSoup(demo, 'html.parser')
print(r.text)
print(soup.a.string)
4、获取Tag内字符串的注释部分Comment:
newsoup = BeautifulSoup("<b><!--这是注释--></b><p>这不是注释</p>", "html.parser")
print(newsoup.b.string)
print(type(newsoup.b.string))
print(newsoup.p.string)
print(type(newsoup.p.string))
Comment是一种特殊的类型,可通过这个判断非属性字符串是否是注释。
3、基于bs4遍历HTML页面的内容
HTMl页面按标签划分是二叉树的形式
所以在进行HTML内容遍历时,可分为横向遍历和纵向遍历。
纵向遍历
向下遍历
soup = BeautifulSoup(demo, 'html.parser')
print(soup.head.contents)
print(soup.body.contents)
for child in soup.body.children:print(child)
向上遍历
soup = BeautifulSoup(demo, 'html.parser')
print(soup.title.parent)
print(soup.html.parent)
for parent in soup.a.parents:if parent is None:print(parent)else:print(parent.name)
横向遍历
平行遍历发生在同一个父节点下的各节点间
soup = BeautifulSoup(demo, 'html.parser')
print(soup)
print(soup.title.next_sibling)
print(soup.body.previous_sibling)
for sibling in soup.a.next_siblings:print(sibling)
for prev in soup.a.previous_siblings:print(prev)
4、基于bs4的HTML的内容查找
搜索方法:find() 和 find_all()
find_all()
<>.find_all(name, attrs, recursive, string, **kwargs)
返回一个列表类型,存储查找的结果
name 对标签名称的检索字符串
可通过name参数进行html页面进行标签名称检索,也可传True,检索全部的标签信息
soup = BeautifulSoup(demo, 'html.parser')
print(soup.find_all('a'))
attrs: 对标签属性值的检索字符串,可标注属性检索
soup = BeautifulSoup(demo, 'html.parser')
print(soup.find_all('p','course'))
print(soup.find_all(id='link1'))
recursive: 是否对子孙全部检索,默认True
soup = BeautifulSoup(demo, 'html.parser')
print(soup.find_all('p'))
print(soup.find_all('p', recursive=False))
string: <>…</>中字符串区域的检索字符串
soup = BeautifulSoup(demo, 'html.parser')
print(soup.find_all(string='Basic Python'))
扩展方法: