网络爬虫系列笔记(3)——Beautiful Soup库

xiaoxiao2021-02-28  90

Unit1: Beautiful Soup           一、安装 https://www.crummy.com/software/BeautifulSoup/ 管理员权限打开命令行:pip install beautifulsoup4(注意:使用pip install beautifulsoup 会失败)  安装测试:演示地址(http://python123.io/ws/demo.html) 网页源码: <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 href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.</p> </body></html> import requests r = requests.get("http://python123.io/ws/demo.html") demo = r.text from bs4 import BeautifulSoup soup = BeautifulSoup(demo, "html.parser") #选择html解析器 #from bs4 import BeautifulSoup #soup = BeautifulSoup('<p>data<p>', "html.parser") print(soup.title) print(soup.a) print(soup.prettify()) soup.a.name soup.a.parent.name 二、Beautiful Soup库的理解、解析 ( bs4全部转换为 UTF-8  ) Beautiful Soup 是解析、遍历、维护“标签树”的功能库。 from bs4 import BeautifulSoup import bs4 等价关系: HTML文档 = 标签树 = BeautifulSoup类 可以将BeautifulSoup类当做对应一个HTML/XML文档的全部。 from bs4 import BeautifulSoup soup = BeautifulSoup("<html>data</html>", "html.parser") soup2 = BeautifulSoup(open("D://demo.html"), "html.parser") BeautifulSoup库的解析器: 解析器 使用方法 条件 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 BeautifulSoup 类的基本元素 Tag 标签,最基本的信息组织单元,分别用<>和</>标明开头和结尾 Name 标签名:<name>...</name>,格式:<tag>.name Attributes 标签属性,字典的形式,格式:<tag>.attrs NavigableString 标签内非属性字符串,<tag>.string Comment 标签内字符串的注释部分,一种特殊的Comment类型"<b><!--This is a comment--></b> IDLE演示: >>> import requests >>> r = requests.get("http://python123.io/ws/demo.html") >>> demo = r.text >>> from bs4 import BeautifulSoup >>> soup = BeautifulSoup(demo, "html.parser") >>> soup.title <title>This is a python demo page</title> >>> soup.a <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a> >>> soup.a.name >>> soup.a.parent.name 'p' >>> soup.a.parent.parent.name 'body' >>> tag = soup.a >>> tag.attrs {'class': ['py1'], 'href': 'http://www.icourse163.org/course/BIT-268001', 'id': 'link1'} >>> tag.attrs['class'] ['py1'] >>> tag.attrs['href'] 'http://www.icourse163.org/course/BIT-268001' >>> type(tag.attrs) <class 'dict'> >>> type(tag) <class 'bs4.element.Tag'> >>> soup.a.string 'Basic Python' >>> soup.p.string 'The demo python introduces several python courses.' >>> type(soup.p.string) <class 'bs4.element.NavigableString'> 三、BeautifulSoup的遍历 1、标签树的下行遍历 .contents 子节点的列表,将<tag>所有儿子节点存入列表 .children 子节点的迭代类型,作用同上,只能用在for...in的结构中。 .descendants 子孙节点的迭代类型,包含所有子孙节点,只能用在for...in的结构中 soup = BeautifulSoup(demo, 'html.parser') soup.body.contents fon child in soup.body.children:      print(child) 2、 标签树的上行遍历 .parent 节点的父亲标签 .parents 节点先辈标签的迭代类型,只能用在for...in的结构中 soup = BeautifulSoup(demo, 'html.parser') for parent in soup.a.parents:      if parent is None: #soup.parent.name == None           print(parent)      else:           print(parent.name) 3、标签树的平行遍历(所有平行遍历都在 同一个父亲节点 下,存在NevigableString类型) .next_sibling .previous_sibling (迭代类型,只能用在for...in的结构中) .next_siblings .previous_siblings (迭代类型,只能用在for...in的结构中 for sibling in soup.a.next_siblings:      print(sibling) for sibling in soup.a.previous_siblings:      print(sibling) 四、其他方法 1、bs4 库的prettify()函数: 显示更漂亮(增加换行符) soup = BeautifulSoup(demo, 'html.parser') soup.prettify() soup.a.prettify()
Unit2 : 信息的 组织 与 提取 1、信息的标记 HTML :Hyper text makeup luaguage 信息的关系 信息的标记de 三种形式: XML:     eXtensible Makeup Language       <name> ... </name>      <name / >      <!--     --> JSON:     JavaScript Object Notation (有数据类型的键值对 key : value)               “key" :“value”             "key" :["value1" , "value2"]             "key" : { "subkey" : "subvalue"} “name” : [“北京理工大学”,“北京大学”]           多值用[ , ]组织      可以嵌套使用  { , }:"name":{                                         "newname" : "北京理工大学",                                          "oldName" : "延安自然研究院"                                             }       可以直接作为程序的一部分 YAML:  YAML Ain't Markup Lauguage (无类型的键值对)     key : value     key : #Comment    -value    -value     key :         subkey : subvalue    name : 北京理工大学      缩进方式表达所属关系:           name:                newname:北京理工大学                oldname:延安自然研究院       - 表达并列关系:            name:                -北京理工大学                -延安自然研究院        | 表达整块数据 #表示注释 :           text: | #介绍           ****¥%#*****123******#@¥¥@ 总结:      XML :Internet 上的信息交互与传递(HTML是一种XML类)      JSON : 移动应用云端和节点的信息通信,无注释(程序对接口处理的地方)      YAML:各类系统的配置文件中,有注释易读,利用率高 2、信息的提取 方法一:完整解析信息的标记形式,再提取关键信息,形式解析      需要标记解析器 如:bs4库的标签树遍历      优点:解析准确      缺点:繁琐且慢 方法二:无视标记形式,直接搜索关键信息,搜索方法      搜索:利用查找函数即可      优点:简洁且快      缺点:确度不定,与内容有关 实际中:二者融合      实例一:提取HTML中所有的URL链接 from bs4 import BeautifulSoup soup = BeautiflulSoup(demo, "html.parser") for link in soup.find_all('a'):      print(link.get('href'))       <>.find_all ( name, attrs, recursive, string, ##kwargs )      返回一个列表类型,储存查找的结果      简短形式:<tag>(...) 等价于 <tag>.find_all(..)                       soup(...)   等价于 soup.find_all(..)       name: soup.find_all('a') soup.find_all(['a','b']) for tag in soup.find_all(True):      print(tag.name) import re for tag in soup.find_all(re.compile('b')): #所有以b开头的标签     print(tag.name)       attrs: soup.find_all('p', 'course')  #查找页面中所有属性值为字符串'course'的p标签 soup.find_all(id='link1') # 对属性进行查找的时候必须精确的复制这个信息 import re soup.find_all(id=re.compile('link'))      recursive: 是否对子孙全部检索,默认True, Bool值 soup.find_all('a', recursive = False) #只查找当前节点的儿子节点      string: <>...</>对标签中的字符串域进行检索 soup.find_all(string = 'Basic Python') import re soup.find_all(string = re.compile('Python'))      find_all的扩展方法:      <>.find(), <>.find_parents(), <>.find_parent(), <>.find_next_sibling(), <>find_next_siblings(), <>.find_previous_sibling(), <>.find_previous_sibllings().
Unit3 : 爬虫实例一 中国大学排名爬取 功能描述: 输入:大学排名URL链接 输出:大学排名信息的屏幕输出(排名,大学名称,总分) 技术路线:requests-bs4 定向爬虫:仅对输入URL进行爬取,不扩展爬取。 静态、定向 步骤一:从网络上获取大学排名网页内容      getHTMLText() 步骤二:提取网页内容的信息到合适的数据结构中      fillUnivList() 步骤三:利用数据结构展示并输出结果      printUnivList() 程序的结构设计:二维列表 import requests from bs4 import BeautifulSoup import bs4 def getHTMLText(url):     try:         r = requests.get(url, timeout = 20)         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): #排除其中的string类型             tds = tr('td')             ulist.append([tds[0].string, tds[1].string,tds[3].string]) def printUnivList(ulist, num):  #需要格式化输出: "{}{}" .format()     tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"     print(tplt.format("排名","学校名称","总分", chr(12288))) #解决 中文输出排版的问题     for i in range(num):         u = ulist[i]         print(tplt.format(u[0],u[1],u[2], chr(12288))) def main():     uinfo = []     url = "http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html"     html = getHTMLText(url)     fillUnivList(uinfo, html)     printUnivList(uinfo, 20) #20 univs main() 优化: 1、中文对齐问题 format()函数: '{0}'    ' {0[1]}{1[0]} '    '{:<>^8}'     '{ : .f}'    '{ : b c d o x X}' 因为位置填充采用的是西文字符空格填充,所以中文对齐会不理想。 从而, 采用中文字符的空格填充chr(12288) tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"     print(tplt.format("排名","学校名称","总分", chr(12288)))
转载请注明原文地址: https://www.6miu.com/read-33723.html

最新回复(0)