做汤1

使用Beautiful Soup库,先看一个例子:

#利用beautiful soup解析网页源代码
#首先利用requests库获取网页源代码
import requests
url='https://python123.io/ws/demo.html'
r=requests.get(url)
r.status_code
demo=r.text
print(demo)#得到网页源代码

from bs4 import BeautifulSoup
soup=BeautifulSoup(demo,'html.parser')#后者是一个解析器
print(soup.prettify())#显示解析后的网页代码

下面介绍BS库的基本元素:

BS库时解析、遍历、维护”标签树“的功能库,标签树可理解为一个字符串,就是<>...<>之间的内容

我们认为  html文档-标签树-Beautiful Soup类是等价的

BS库解析器;

解析器 使用方法 条件
bs4的HTML解析器 BeautifulSoup(mk,'html.parser') 安装bs4库
lxml的HTML解析器 BeautifulSoup(mk,'lxml') pip install lxml
lxml的XML解析器 BeautifulSoup(mk,'xml') pip install lxml
html5lib的解析器 BeautifulSoup(mk,'html5lib') pip install html5lib

BS类的基本元素

基本元素 说明
Tag 标签,最基本的信息组织单元,分别用<>和</>表明开头和结尾
Name 标签的名字,<p>...</p>的名字是'p',格式是:<tag>.name
Attributes 标签的属性,字典形式组织,格式:<tag>.attrs
NavigableString 标签内非属性字符串,<>...</>中字符串,格式:<tag>.string
Comment 标签内字符串的注释部分,一种特殊的Comment类型

解析后的网页代码:

<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>

根据以上的网页代码,我们可以看到查看一些标签:

soup.title#输出<title>This is a python demo page</title>
tag=soup.a
tag#输出<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
soup.a.name#输出'a'
soup.a.parent.name#输出'p'
soup.p.parent.name#输出'body'
tag.attrs#标签属性,输出{'class': ['py1'],
 'href': 'http://www.icourse163.org/course/BIT-268001',
 'id': 'link1'}
#获取标签属性class的值
tag.attrs['class']#输出['py1']
#获取标签属性链接的值
tag.attrs['href']#输出'http://www.icourse163.org/course/BIT-268001'
type(tag.attrs)#输出dict
type(tag)#输出bs4.element.Tag

NavigableString属性的查看:

soup.a.string#输出'Basic Python'
type(soup.a.string)#输出bs4.element.NavigableString

soup.p.string#输出'The demo python introduces several python courses.'
type(soup.p.string)#输出bs4.element.NavigableString

我们发现p标签string输出中没有b标签,说明NavigableString可以跨越多个层次。

总结:

原文地址:https://www.cnblogs.com/rayshaw/p/8569135.html