Python旅途遇到遊樂園——爬蟲入門 ( 二 )

我想我應該告訴你們我又幹了什麼憨批事

今天來玩BeautifulSoup庫
我們之前已經學會了用Requests庫進行簡單的爬取,複習一下:

import requests
url = 'http://python123.io/ws/demo.html'
try:
    r = requests.get(url)
    r.raise_for_status()
    # 異常處理
    r.encoding = r.apparent_encoding  # 記住ta
    print(r.text[:1000])
except:
    print('爬取失敗')

今天我們要接觸的BeautifulSoup庫,是編寫Python爬蟲常用庫之一,主要用來解析html標籤
我們可以先來試驗一下:

import requests
from bs4 import BeautifulSoup
url = 'http://python123.io/ws/demo.html'
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo , 'html.parser')
print(soup.prettify)

精簡一下,BeautifulSoup的使用方法就是兩句話:

from bs4 import BeautifulSoup
soup = BeautifulSoup('<p>data</p>' , 'html.parser')

開局我們從bs4庫中引入了一個BeautifulSoup類型
BeautifulSoup類型有兩個參數:

  • '<p>data</p>':html格式的信息
  • 'html.parser':解析器(在這裏我們選擇了html.parser)

BeautifulSoup庫的基本元素

任何一個html文件,都是由若干個尖括號構成的標籤組織起來的
而BeautifulSoup庫是解析,遍歷,維護 " 標籤樹 " 的功能庫
只要提供的文件是標籤類型,BeautifulSoup庫就可以對其進行解析

html標籤:
<p>..</p>:Tag<p>..</p>:標籤Tag
<p class="title">...</p><p\ class="title">...</p>

  • 名稱Name成對出現:p ⬅➡ /p
  • 屬性Attributes有0個或多個:class=“title”

BeautifulSoup庫解析器

解析器 使用方法 條件
bs4的HTML解析器 BeautifulSoup(mk,‘html.parser’) pip install beautifulsoup4
Ixml的HTML解析器 BeautifulSoup(mk,‘lxml’) pip install lxml
lxml的XML解析器 BeautifuSoup(mk,‘xml’) pip install lxml
html5lib解析器 BeautifulSoup(mk,‘html5lib’) pip install html5lib

BeautifulSoup庫的基本元素

基本元素 說明
Tag 標籤,最基本的信息組織單元,分別用< >和< / >標明開頭和結尾
Name 標籤的名字,< p >…< /p >的名字是‘p’,格式:< tag >.name
Attributes 標籤的屬性,字典形式組織,格式:< tag >.attrs
NavigableString 標籤內非屬性字符串,< >…< / >中的字符串,格式:< tag >.string
Comment 標籤內字符串的註釋部分,一種特殊的Comment類型

在這裏插入圖片描述

import requests
from bs4 import BeautifulSoup
url = 'http://python123.io/ws/demo.html'
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo , "html.parser")

>>> soup.title
<title>This is a python demo page</title>

>>> soup.a.name
'a'
>>> soup.a.parent.name
'p'
>>> soup.a.parent.parent.name
'body'

>>> soup.a
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
>>> tag = soup.a
>>> tag.attrs
{'href': 'http://www.icourse163.org/course/BIT-268001', 'class': ['py1'], '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
<p class="title"><b>The demo python introduces several python courses.</b></p>
>>> soup.p.string
'The demo python introduces several python courses.'
>>> type(soup.p.string)
<class 'bs4.element.NavigableString'>

>>> newsoup = BeautifulSoup('<b><!--This is a comment--></b><p>This is not a comment</p>','html.parser')
>>> newsoup.b.string
'This is a comment'
>>> type(newsoup.b.string)
<class 'bs4.element.Comment'>
>>> newsoup.p.string
'This is not a comment'
>>> type(newsoup.p.string)
<class 'bs4.element.NavigableString'>

基於bs4庫的HTML內容遍歷方法

首先介紹HTML基本格式
在這裏插入圖片描述

標籤樹的下行遍歷

屬性 說明
.contents 子節點的列表,將< tag >所有兒子節點存入列表
.children 子節點的迭代類型,與.contents類似,用於循環遍歷兒子節點
.descendants 子孫節點的迭代類型,包含所有子孫節點,用於循環遍歷
import requests
from bs4 import BeautifulSoup
url = 'http://python123.io/ws/demo.html'
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo , "html.parser")

>>> soup.head
<head><title>This is a python demo page</title></head>
>>> len(soup.body.contents)
5
>>> soup.body.contents[1]
<p class="title"><b>The demo python introduces several python courses.</b></p>
>>> 

遍歷兒子:

for child in soup.body.children:
    print(child)

遍歷子孫:

for child in soup.body.descendants:
    print(child)

標籤樹的上行遍歷

屬性 說明
.parent 節點的父親節點
.parents 節點先輩標籤的迭代類型,用於循環遍歷先輩節點
>>> soup.title
<title>This is a python demo page</title>
>>> soup.title.parent
<head><title>This is a python demo page</title></head>
import requests
from bs4 import BeautifulSoup
url = 'http://python123.io/ws/demo.html'
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo , "html.parser")
for parent in soup.a.parents:
    if parent is None:
        print(parent)
    else:
        print(parent.name)

##########################################

p
body
html
[document]

標籤樹的平行遍歷

屬性 說明
.next_sibling 返回按照HTML文本順序的下一個平行節點標籤
.previous_sibling 返回按照HTML文本順序的上一個平行節點標籤
.next_siblings 迭代類型,返回按照HTML文本順序的後續所有平行節點標籤
.previous_siblings 迭代類型,返回按照HTML文本順序的前序所有平行節點標籤

遍歷後續節點:

for sibling in soup.a.next_siblings:
    print(sibling)

遍歷前序節點:

for sibling in soup.a.previous_siblings:
    print(sibling)

總結一下

在這裏插入圖片描述


基於bs4庫的HTML格式化和編碼

prettify()

>>> soup.prettify()
'<html>\n <head>\n  <title>\n   This is a python demo page\n  </title>\n </head>\n <body>\n  <p class="title">\n   <b>\n    The demo python introduces several python courses.\n   </b>\n  </p>\n  <p class="course">\n   Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\n   <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">\n    Basic Python\n   </a>\n   and\n   <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">\n    Advanced Python\n   </a>\n   .\n  </p>\n </body>\n</html>'
>>> print(soup.prettify())
<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>

基於bs4庫的HTML內容查找方法

<>.find_all(name,attrs,recursive,string,**kwargs)

返回一個列表類型,存儲查找的結果

  • name:對標籤名稱的檢索字符串
  • attrs:對標籤屬性值的檢索字符串,可標註屬性檢索
  • recursive:是否對所有子孫進行檢索,默認爲True
  • string:<>…</>中字符串區域的檢索字符串
>>> soup.find_all('a')
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]

擴展方法:

方法 說明
.find() 搜索且只返回一個結果,字符串類型,同.find_all()參數
.find_parents() 在先輩節點中搜索,返回列表類型,同.find_all()參數
.find_parent() 在先輩節點中返回一個結果,字符串類型,同.find()參數
.find_next_sibling() 在後續平行節點中搜索,返回列表類型,同.find_all()參數
.find_next_siblings() 在後續平行節點中返回一個結果,字符串類型,同.find()參數
.find_previous_sibling() 在前序平行節點中搜索,返回列表類型,同.find_all()參數
.find_previous_siblings() 在前序平行節點中返回一個結果,字符串類型,同.find()參數

實例:中國大學排名定向爬蟲

功能描述

輸入:大學排名URL鏈接
輸出:大學排名信息的屏幕輸出(排名,大學名稱,總分)
技術路線:requests-bs4
定向爬蟲:僅對輸入的URL進行爬取,不擴展爬取

這就是我們今天行動的目標
我們查看一下robots.txt,發現404了,那就甩開膀子爬吧

程序的結構設計

步驟一:從網站上獲取大學排名網頁內容(getHTMLText()getHTMLText()
步驟二:提取網站內容中信息到合適的數據結構(fillUnivList()fillUnivList()
步驟三:利用數據結構展示並輸出結果(printUnivList()printUnivList()

import requests
from bs4 import BeautifulSoup
import bs4

def getHTMLText(url):  # 爬取模板
    try:
        r = requests.get(url)
        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:  # 通過閱讀源代碼得知信息都在tbody中
        if isinstance(tr,bs4.element.Tag):  # 過濾非Tag類型的信息
            tds = tr('td')
            ulist.append([tds[0].string , tds[1].string , tds[3].string])

def printUnivList(ulist,num):
    print('{:^10}\t{:^20}\t{:^10}'.format('排名','學校名稱','總分'))
    for i in range(num):
        u = ulist[i]
        print('{:^10}\t{:^20}\t{:^10}'.format(u[0],u[1],u[2]))    

def main():
    uinfo = []
    url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2019.html'
    html = getHTMLText(url)
    fillUnivList(uinfo,html)
    printUnivList(uinfo,20)  # 20 univs

main()

在這裏插入圖片描述

文章的最後,簡單解釋一下這幾行代碼的用意:

for tr in soup.find('tbody').children:  # 通過閱讀源代碼得知信息都在tbody中
    if isinstance(tr,bs4.element.Tag):  # 過濾非Tag類型的信息
         tds = tr('td')
         ulist.append([tds[0].string , tds[1].string , tds[3].string])

通過閱讀源代碼,我們會發現我們需要的關鍵信息都在tbody之下 ( children ) 的tr標籤
tr標籤內找到所有的td標籤,並存儲爲列表類型:tds = tr('td')(等價於tds = tr.find_all('td')
因爲學校排名+學校名稱+總分都是td標籤的NavigableString,所以需要取tr標籤的string
在這裏插入圖片描述

發佈了956 篇原創文章 · 獲贊 211 · 訪問量 33萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章