閱讀目錄
一 什么是BeautifulSoup
簡單來說,Beautiful Soup是python的一個庫,最主要的功能是從網頁抓取數據。
官方解釋如下:
Beautiful Soup提供一些簡單的、python式的函數用來處理導航、搜索、修改分析樹等功能。它是一個工具箱,通過解析文檔為用戶提供需要抓取的數據,因為簡單,所以不需要多少代碼就可以寫出一個完整的應用程序。
Beautiful Soup 是一個可以從HTML或XML文件中提取數據的Python庫。它能夠通過你喜歡的轉換器實現慣用的文檔導航,查找,修改文檔的方式。所以需要配合解析器一起使用!
Beautiful Soup會幫你節省數小時甚至數天的工作時間.你可能在尋找 Beautiful Soup3 的文檔,Beautiful Soup 3 目前已經停止開發,官網推薦在現在的項目中使用Beautiful Soup 4。
解析器:
Beautiful Soup支持Python標准庫中的HTML解析器,還支持一些第三方的解析器,如果我們不安裝它,則 Python 會使用 Python默認的解析器,lxml 解析器更加強大,速度更快,推薦安裝另一個可供選擇的解析器是純Python實現的 html5lib , html5lib的解析方式與瀏覽器相同。
解析器對比: 官方文檔

# 安裝 Beautiful Soup pip3 install beautifulsoup4 #安裝解析器 ''' Beautiful Soup支持Python標准庫中的HTML解析器,還支持一些第三方的解析器,其中一個是 lxml .根據操作系統不同,可以選擇下列方法來安裝lxml: apt-get install Python-lxml pip3 install lxml 另一個可供選擇的解析器是純Python實現的 html5lib , html5lib的解析方式與瀏覽器相同,可以選擇下列方法來安裝html5lib: apt-get install Python-html5lib pip3 install html5lib '''
二 為什么要用BeautifulSoup?
BeautifulSoup能給我們提供一些列查找文檔樹的方法,使我們能快速定位到我們想要爬取的數據。我們再回想一下之前學的一個re模塊,它可以全局查找我們想要的文本,從文本開頭到結束開始匹配,然后通過貪婪匹配,再通過非貪婪匹配拿到需要的數據,整個過程是不是非常繁瑣,而卻搜索效率極低!
BeautifulSoup內既封裝了re,還為我們提供了一些更加強大、高效的功能,使我們可以快速匹配到我們想要的數據,提高爬取效率和開發效率。
三 安裝
1、安裝
# 安裝BeautifulSoup4 pip3 install beautifulsoup4 # 安裝解析器 # 根據官網解釋,推薦使用lxml pip3 install lxml
四 怎么使用
1、基本使用
注意: 如何初始文本內有換行,也會算在里面。(坑)
html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="sister"><b>$37</b></p> <p class="story" id="p">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" >Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ from bs4 import BeautifulSoup # 第一個參數是解析文本 # 第二個參數是解析器 soup = BeautifulSoup(html_doc, 'lxml') # 具備自動補全html標簽功能 print(soup) # 美化html便簽 html_doc = soup.prettify() print(html_doc)
2、遍歷文檔樹
''' 1、直接使用 2、獲取標簽的名稱 3、獲取標簽的屬性 4、獲取標簽的內容 5、嵌套選擇 6、子節點、子孫節點 7、父節點、祖先節點 8、兄弟節點 '''

from bs4 import BeautifulSoup # 注意: 如何初始文本內有換行,也會算在里面。(坑) html_doc = """ <html><head><title>The Dormouse's story</title></head><body><p class="sister"><b>$37</b></p><p class="story" id="p">Once upon a time there were three little sisters; and their names were<a href="http://example.com/elsie" class="sister" >Elsie</a><a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>and they lived at the bottom of a well.</p><p class="story">...</p> """ # 第一個參數是解析文本 # 第二個參數是解析器 soup = BeautifulSoup(html_doc, 'lxml') # 具備自動補全html標簽功能 # print(soup) # 美化html便簽 html_doc = soup.prettify() # print(html_doc) # soup = BeautifulSoup(html_doc, 'lxml') # 1、直接選擇標簽(返回的是一個對象) print(soup.a) # 獲取第一個a標簽 print(soup.p) # 獲取第一個p標簽 print(type(soup.a)) # <class 'bs4.element.Tag'> # 2、獲取標簽的名稱 print(soup.a.name) # 獲取a標簽的名字 # 3、獲取標簽的屬性 print(soup.a.attrs) # 獲取a標簽內所有的屬性 # 4、獲取標簽的內容 print(soup.a.attrs['href']) # 獲取a標簽內的href屬性 # 5、嵌套選擇標簽 print(soup.p.b) # 獲取第一個p標簽內的b標簽 print(soup.p.b.text) # 打印b標簽內的文本 # 6、子節點、子孫節點 # 獲取子節點 print(soup.p.children) # 獲取第一個p標簽所有的子節點,返回的是一個迭代器 print(list(soup.p.children)) # list轉成列表 # 獲取子孫節點 print(soup.body.descendants) # 獲取body標簽內所有的子孫節點,返回的是一個生成器 print(list(soup.body.descendants)) # list轉成列表 # 獲取第一個p標簽中所有的內容,返回的是一個列表 print(soup.p.contents) # 7、父節點、祖先節點 # 獲取父節點 print(soup.a.parent) # 獲取第一個a標簽內的父節點 # 獲取祖先節點(爸爸,爸爸的爸爸,爸爸的爸爸的爸爸...以此類推) print(list(soup.a.parents)) # 獲取第一個a標簽的祖先節點,返回的是一個生成器 print('*' * 1000) # 8、兄弟節點 (sibling: 兄弟姐妹) print(soup.a) # 獲取下一個兄弟節點 print(soup.a.next_sibling) # 獲取下一個的所有兄弟節點,返回的是一個生成器 print(soup.a.next_siblings) print(list(soup.a.next_siblings)) # 獲取上一個兄弟節點 print(soup.a.previous_sibling) # 獲取上一個的所有兄弟節點,返回的是一個生成器 print(list(soup.a.previous_siblings))
3、搜索文檔樹
BeautifulSoup定義了很多搜索方法,這里着重介紹2個:find() 和 find_all() 。其它方法的參數和用法類似!
''' 標簽查找與屬性查找: 標簽: - 字符串過濾器 字符串全局匹配 name 屬性匹配 attrs 屬性查找匹配 text 文本匹配 - 正則過濾器 re模塊匹配 - 列表過濾器 列表內的數據匹配 - bool過濾器 True匹配 - 方法過濾器 用於一些要的屬性以及不需要的屬性查找。 屬性: - class_ - id '''

from bs4 import BeautifulSoup import re # 注意: 如何初始文本內有換行,也會算在里面。(坑) html_doc = """ <html><head><title>The Dormouse's story</title></head><body><p class="sister"><b>$37</b></p><p class="story" id="p">Once upon a time there were three little sisters; and their names were<a href="http://example.com/elsie" class="sister" >Elsie</a><a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>and they lived at the bottom of a well.</p><p class="story">...</p> """ # 第一個參數是解析文本 # 第二個參數是解析器 soup = BeautifulSoup(html_doc, 'lxml') ''' 標簽查找與屬性查找: 標簽: - 字符串過濾器 字符串全局匹配 name 屬性匹配 attrs 屬性查找匹配 text 文本匹配 - 正則過濾器 re模塊匹配 - 列表過濾器 列表內的數據匹配 - bool過濾器 True匹配 - 方法過濾器 用於一些要的屬性以及不需要的屬性查找。 屬性: - class_ - id ''' # 1、字符串 # find的默認參數 第一個是name、第二個是attrs、第四個是text # name: 根據標簽名匹配節點 print(soup.find('p')) # 獲取第一個p標簽 print(soup.find_all(name='p')) # 獲取所有的p標簽 # attrs: 根據屬性查找匹配節點 print(soup.find(attrs={'id': 'p'})) # 查找id為p的標簽 print(soup.find_all(attrs={'class': 'sister'})) # 查找class為sister的所有標簽 # text: 根據文本匹配文檔樹內的文本 # 推薦配合其他匹配規則使用,否則毫無意義 print(soup.find(text='$37')) # 查找標簽內為$37的文本 # name與text配合使用 print(soup.find_all(name='p', text='$37')) # 查找所有文本為$37的p標簽 # name與attrs配合使用 print(soup.find(name='a', attrs={'id': 'link2'})) # 查找第一個id為link2的a標簽 # attrs與text配合使用 print(soup.find_all(attrs={'id': 'link2'}, text='Lacie')) # 查找所有id為link2,文本為Lacie的標簽 # name、attrs、text組合使用 print(soup.find_all(name='a', attrs={'id': 'link3'}, text='Tillie')) # 查找所有id為link3,文本為Tillie的a標簽 # 2、正則 print(soup.find(name=re.compile('a'))) # 通過第一個標簽名帶有a的節點 print(soup.find_all(attrs={'id': re.compile('link')})) # 匹配所有id名帶有link的節點 print(soup.find_all(text=re.compile('and'))) # 匹配所有文本帶有"and"的節點 # 3、列表 (列表內可以匹配多個) print(soup.find_all(name=['a', re.compile('e')])) # 匹配所有a標簽節點與所有標簽中帶有e的節點 print(soup.find_all(text=['$'])) # 找不到,因為$是精確查找 print(soup.find_all(text=['$37'])) # 查找$37文本,這樣查找是沒有意義的 print(soup.find_all(text=[re.compile('\$')])) # 正則中$是特殊字符,所以需要轉義 # 4、bool print(soup.find_all(name=True)) # 查找所有有標簽名的節點 print(soup.find_all(attrs={'id': True})) # 查找所有有id的節點 print(soup.find_all(text=True)) # 查找所有文本 # 5、方法 # 寫一個只要有class沒有id的a標簽的函數 def has_class_not_id(arg): if arg.name == 'a' and arg.has_attr('class') and not arg.has_attr('id'): return arg.name print(soup.find_all(name=has_class_not_id)) # 通過has_class_not_id的函數匹配節點 # 6、標簽與屬性查找 # 標簽 print(soup.find_all(attrs={'class': 'sister'})) # 屬性 # 根據class屬性查找,因為class是關鍵字,所以后面需要加下划線 print(soup.find_all(class_='sister')) # 根據id屬性查找 print(soup.find_all(id='link2'))
五 自動登錄抽屜新熱榜並點贊與評論

''' # 抽屜新熱榜自動登陸並點贊 1.需要攜帶評論主頁的cookies信息去進行點贊,否則點贊失敗 ''' from bs4 import BeautifulSoup import requests # 通過bs4解析庫獲取所有新聞的id for line in range(2, 4): index_url = 'https://dig.chouti.com/all/hot/recent/{0}'.format(line) response1 = requests.get(index_url, headers={ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36' } ) response1_cookies = response1.cookies soup = BeautifulSoup(response1.text, 'html.parser') items = soup.find_all(attrs={'class': 'item'}) # print(items) for item in items: div_tag = item.find(attrs={'class': 'part2'}) # print(div) # print(type(div)) # 拿到所有的id user_id = div_tag.get('share-linkid') # print(user_id) form_data = { "phone": "8615622792660", "password": "kermit46709394", "oneMonth": '1' } # print(url) response2 = requests.post('https://dig.chouti.com/login', headers={ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36' }, data=form_data, cookies=response1_cookies ) url = 'https://dig.chouti.com/link/vote?linksId={user_id}'.format(user_id=user_id) # 抽屜新熱榜自動點贊 response3 = requests.post(url, headers={ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36' }, cookies=response1_cookies ) print(response3.text)