Beautifulsoup學習筆記+實戰項目(絕對詳細)

安裝

pip install beautifulsoup4

卸載:

pip uninstall beautifulsoup4
## import
import requests
import os
from bs4 import BeautifulSoup
import bs4
import re

demo

r = requests.get("網址")
r.encoding = r.apparent_encoding
demo = r.text
soup = BeautifulSoup(demo, 'html.parser')
res = list()
for item in soup.find_all('a', string=re.compile('疫')):
    res.append(item.string)
print(res)

上面可以簡單的看作一段代碼,大致意思就是在網頁上尋找中含有“疫”的內容。
具體的用法會在後面給出。

Beautifulsoup操作

首先我們先明確html的基本結構
在這裏插入圖片描述
是很明顯的樹狀結構。

基本元素

在這裏插入圖片描述

	查看標籤a的屬性
輸入: tag=soup.a
      tag.attrs
    查看標籤a的屬性中class的值
輸入:tag.attrs['class']
	查看標籤a的屬性 的類型
輸入:type(tag.attrs)

遍歷

在這裏插入圖片描述
在這裏插入圖片描述

注:.contents 和 .children 屬性僅包含tag的直接子節點,.descendants 屬性可以對所有tag的子孫節點進行遞歸循環,和 children類似,我們也需要遍歷獲取其中的內容。

·標籤樹的下行遍歷
獲得孩子節點的個數
len(soup.body.contents)
分別輸出各個子節點
soup.body.contents[2]

·標籤樹的上行遍歷
獲得a節點的父節點名稱
soup.a.parent.name
獲得a節點的所有先輩點名稱
for parent in soup.a.parents:
	print(parent.name)
	注:遍歷所有先輩節點,包括soup本身

·標籤樹的平行遍歷
獲得a節點的上一個節點和下一個節點
soup.a.next_sibling
soup.a.previous_sibling

在這裏插入圖片描述
## bs4庫的prettify()方法
.prettify()爲HTML文本<>及其內容增加換行符可以用於整個HTML文本,也可以用於單個標籤方法:
.prettify()
在這裏插入圖片描述
注:bs4庫將任何HTML輸入都變成utf‐8編碼Python 3.x默認支持編碼是utf‐8,解析無障礙
## 信息檢索

import requests
r=requests.get("http://www.baidu.com/")
r.encoding=r.apparent_encoding
demo=r.text
from bs4 import BeautifulSoup
soup=BeautifulSoup(demo, 'html.parser')
print(soup.find_all('a'))
<>.find_all(name,attrs,recursive,string,**kwargs)

name:    對標籤名稱的檢索字符串
attrs:     對標籤屬性值的檢索字符串,可標註屬性檢索
recursive: 是否對子孫全部檢索,默認True
string: <></>中字符串區域的檢索字符串

擴展方法:
在這裏插入圖片描述

實戰爬取

爬取百度熱門人物排行

# 2.2
r = requests.get('http://top.baidu.com/buzz?b=257&c=9&fr=topcategory_c9')
r.encoding = r.apparent_encoding
demo2 = r.text
soup2 = BeautifulSoup(demo2, 'html.parser')
res2 = list()
for i in soup2.find_all('a', 'list-title'):
    res2.append(i.string)
for index,i in enumerate(res2):
    print(index,i)

在這裏插入圖片描述

大學排名爬取

# 2.3
url3 = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html'
r = requests.get(url3)
r.encoding = r.apparent_encoding
demo3 = r.text
soup3 = BeautifulSoup(demo3, 'html.parser')
res3 = list()
for item in soup3.find('tbody').children:
    tmp = list()
    if isinstance(item, bs4.element.Tag):
        tdList = item('td')
        tmp.append(tdList[0].string)
        tmp.append(tdList[1].string)
        tmp.append(tdList[3].string)
        res3.append(tmp)

在這裏插入圖片描述
注:
定義的輸出格式模板變量,^代表居中,4/12/10代表輸出寬度(當輸出數據超過該數字時,以實際輸出爲準),{3}代表打印輸出時,我們使用format中的第3個變量(由0起始),也就是 chr(12288)
chr(12288)代表全角Unicode空格(即中文空格)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章