本节的内容,采用Beautiful Soup来解析HTML页面。 
Beautiful Soup可对网页页面进行树形解析,使用原理是  比如
import requests
r=requests.get("https://python123.io/ws/demo.html")
r.text
demo=r.text
from bs4 import BeautifulSoup
soup=BeautifulSoup(demo,"html.parser")
print(soup.prettify())
Beautiful Soup 库是解析,遍历、维护“标签树”的功能库,每一对尖括号内都是一个标签。   尖括号内的属性是键值对的形式如class和title  从bs4库里引用其中的类,包括BeautifulSoup,也可以直接引用bs4库  


import requests
r=requests.get("https://python123.io/ws/demo.html")
r.text
demo=r.text
from bs4 import BeautifulSoup
soup=BeautifulSoup(demo,"html.parser")
##print(soup.prettify())
##soup.title
##tag=soup.a
soup.p
print(tag)
soup.a.name
soup.a.parent.name
soup.a.parent.parent.name
###标签的属性
tag=soup.a
tag.attrs
###因为标签的属性是字典的形式,因此可以通过字典来获取
tag.attrs['href']
###标签属性类型
type(tag.attrs)
type(tag)
##查看标签内的字符串信息
soup.a.string
soup.p.string
type(soup.p.string)##bs4库的元素类型bs4.element.NavigableString

BeautifulSoup库的使用总结 

 标签树的下行遍历 

      
信息标记  
信息标记的种类 包括三种 XML eXtensible Markup Language  
JSON JavsScript Object Natatio 有类型的键值对构成的表达方式 
YAML YAML Ain’t Markup Language 为一种递归的定义 采用无类型的键值对类型(键值对中无双引号)  通过缩进来表示键值对的所属关系  用-(减号表示并列) 
YAML采用竖线表示整块数据#表示注释  
三种信息标记形式的比较
标记形式 | 特点 |
---|
XML | 采用尖括号进行标记 | JSON | 采用有类型的键值对进行信息标记 | YAML | 采用无类型键值对的表达形式 |
    
信息提取的一般方法: 从标记后的信息中,提取关注的信息
-
方法1.完整的解析信息的标记形式,再提取关键信息。 XML、JSON、YAML 需要标记解释器,如bs4库的标签遍历树 优点:信息解析准确 缺点:提取过程繁琐,速度慢。 -
方法2:无视标记形式,直接搜索关键信息。 对信息的文本查找函数即可。 优点:提取过程简洁,速度较快。 缺点:提取结果准确性与信息内容相关。 -
融合的方法(可采用BeautifulSoup进行实现) 结合形式解析与搜索方法,提取关键信息。 XML、JSON、YAML搜索 需要标记解析器文本查找函数。 实例 
import requests
kv={"user-agent":"Mozilla/5.0"}
r=requests.get("https://python123.io/ws/demo.html",headers=kv)
r.text
demo=r.text
from bs4 import BeautifulSoup
soup=BeautifulSoup(demo,'html.parser')
soup.find_all('a')
soup.text
for link in soup.find_all('a'):
print(link.get('href'))
基于BeautifulSoup库的HTML查找方法 <>find_all(name, attrs,recursive,string,**kwargs)
 soup.find_all(True)表示显示所有的标签  基于BeautifulSoup库的HTML查找方法 <>find_all(name, attrs,recursive,string,**kwargs)
- attrs:对标签属性值的检索字符串,可标注属性检索。
 
基于BeautifulSoup库的HTML查找方法 <>find_all(name, attrs,recursive,string,**kwargs)
- recursive:是否对子孙全部检索,默认True。

基于BeautifulSoup库的HTML查找方法 <>find_all(name, attrs,recursive,string,**kwargs)
- string:<>…</>字符串区域的检索字符串。

 BeautifulSoup的7个find方法  实例学习,中国大学排名自动爬取  程序的结构设计
- 步骤1:从网络上获取大学排名我网页内容
- 步骤2:提取网页中信息到合适的数据结构
- 步骤3:利用数据结构展示并输出结果
 主要的解决方法:
- 步骤1:从网络上获取大学排名网页内容getHTMLText()
- 步骤2:提取网页内容中的信息到合适的数据结构fillUnivList()
- 步骤3:利用数据结构展示并输出结果printUnivList()
 
#CrawUnivRankingB.py
import requests
from bs4 import BeautifulSoup
import bs4
def getHTMLText(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
def fillUnivList(ulist, html):
soup = BeautifulSoup(html, "html.parser")
for tr in soup.find('tbody').children:
if isinstance(tr, bs4.element.Tag):
tds = tr('td')
ulist.append([tds[0].string,tds[1].div.a.string,tds[4].string])
def printUnivList(ulist, num):
tplt = "{0:{3}^10}\t{1:{3}^10}\t{2:{3}^10}"
print(tplt.format("排名","学校名称","总分",chr(12288)))
for i in range(num):
u=ulist[i]
print(tplt.format(u[0].strip(),u[1].strip(),u[2].strip(),chr(12288)))
def main():
uinfo = []
url = 'https://www.shanghairanking.cn/rankings/bcur/202111'
html = getHTMLText(url)
fillUnivList(uinfo, html)
printUnivList(uinfo, 30) # 20 univs
main()
经过几番修改后,终于打印出了嵩老师教的模样,开心中,可是回头看了一眼,前期学习的内容好像又忘完了。 
|