Python爬虫之旅_(数据解析)_bs4
前言:
這次來學(xué)習(xí)數(shù)據(jù)解析這方面的知識(shí)!
0x00:了解數(shù)據(jù)解析
在ONE那一篇中,就提到過聚焦爬蟲(爬取頁面中指定內(nèi)容),大部分的爬蟲都是聚焦爬蟲,但我們剛開始爬取的肯定都是整個(gè)頁面的數(shù)據(jù),如何定位到我們想要的那一部分?jǐn)?shù)據(jù),就用到了數(shù)據(jù)解析
數(shù)據(jù)解析主要通過以下三種進(jìn)行:
加粗樣式
數(shù)據(jù)解析原理:
—— 解析的局部的文本內(nèi)容都會(huì)在標(biāo)簽之間或者標(biāo)簽對(duì)應(yīng)的屬性中進(jìn)行存儲(chǔ) 一 1.進(jìn)行指定標(biāo)簽的定位 二 2.標(biāo)簽或者標(biāo)簽對(duì)應(yīng)的屬性中存儲(chǔ)的數(shù)據(jù)值進(jìn)行提取(解析)先練習(xí)一下爬取圖片:
爬取圖片
#爬取圖片 import requests if __name__ == "__main__":url = 'http://gaoxiao.jokeji.cn/UpFilesnew/2011/8/20/201182002041961.jpg'#content返回的是二進(jìn)制形式的圖片數(shù)據(jù)img_data = requests.get(url=url).content#text(字符串) content(二進(jìn)制數(shù)據(jù)) json(對(duì)象)with open('imag.jpg','wb') as fp:fp.write(img_data)print('Over')爬取成功:
0x01:使用bs4進(jìn)行解析
bs4數(shù)據(jù)解析的原理: —— 1.實(shí)例化一個(gè)BeautifulSoup對(duì)象,并且將頁面源碼數(shù)據(jù)加載到該對(duì)象中 —— 2.通過調(diào)用BeautifulSoup對(duì)象中相關(guān)的屬性或者方法進(jìn)行標(biāo)簽定位和數(shù)據(jù)提取 如何實(shí)例化BeautifulSoup對(duì)象: —— from bs4 import BeautifulSoup —— 對(duì)象的實(shí)例化:—— 1.將本地的html文檔中的數(shù)據(jù)加載到該對(duì)象中fp = open('sogou.html','r',encoding='utf-8')soup = BeautifulSoup(fp,'lxml')—— 2.將互聯(lián)網(wǎng)上獲取的網(wǎng)頁源碼加載到該對(duì)象中page_text = response.textsoup = BeautifulSoup(page_text,'lxml')—— 提供用于數(shù)據(jù)解析的方法和屬性:soup.tagName:返回的是文檔中第一次出現(xiàn)的tagName對(duì)應(yīng)的標(biāo)簽(單數(shù),只能返回一個(gè))soup.find('tagName'):等同于soup.tagName(單數(shù))—— 屬性定位:——soup.find('div',class_/(還可以是其他的屬性)='bg-gj-w')#下劃線是為了區(qū)分關(guān)鍵字——soup.find_all('a')(多個(gè)數(shù))#返回要求的所有標(biāo)簽(列表)—— select:——soup.select('.dingpai > li > a')# >表示的是一個(gè)層級(jí)——soup.select('.dingpai a')#空格表示的是多個(gè)層級(jí)#層級(jí)選擇器——獲取標(biāo)簽之間的文本數(shù)據(jù):——soup.a.text/string/get_text()——區(qū)別:text/get_text():可以獲取某一個(gè)標(biāo)簽中所有的文本內(nèi)容string:只可以獲取該標(biāo)簽下面直系的文本內(nèi)容 ——獲取標(biāo)簽中屬性值:—— soup.a['href']測(cè)試文檔:
<div class="dingpai"> <li> <a id="ding79" href="javascript:ding('79','http://so.gushiwen.org/shiwenv.aspx?id=8dd719a833f0')">有用</a> <a id="pai79" style=" margin-left:10px;" href="javascript:pai('79','http://so.gushiwen.org/shiwenv.aspx?id=8dd719a833f0')">沒用</a> <a style="width:34px; height:18px; line-height:19px; margin-top:2px; float:right; color:#aeaeae;" href="/jiucuo.aspx?u=%e7%bf%bb%e8%af%9179%e3%80%8a%e8%af%91%e6%96%87%e5%8f%8a%e6%b3%a8%e9%87%8a%e3%80%8b" target="_blank">完善</a> </li> </div>練習(xí)代碼:
from bs4 import BeautifulSoup if __name__ == "__main__":#將本地的html文檔的數(shù)據(jù)加載到該對(duì)象中fp = open('test.html','r',encoding='utf-8')soup = BeautifulSoup(fp,'lxml')# print(soup.a)# print(soup.find('div',class_='dingpai').get_text())# print(soup.find_all('a'))# print(soup.select('.dingpai > li > a')[0])# print(soup.select('.dingpai a')[0])# print(soup.select('.dingpai a')[0].text)# print(soup.select('.dingpai a')[0].get_text())# print(soup.select('.dingpai a')[0]['href'])0x02:爬取三國演義小說
練習(xí)了基本的一些操作,接下來利用這個(gè)模塊爬取一下三國演義的小說:
要做的就是將 標(biāo)題 和 標(biāo)題對(duì)應(yīng)的內(nèi)容爬取保存到本地
一開始還是先要爬取整個(gè)頁面的數(shù)據(jù)(通用爬蟲):
import requests from bs4 import BeautifulSoupif __name__ == '__main__':#URLurl = 'http://shicimingju.com/book/sanguoyanyi.html'#UA偽裝headers = {'User-Agent' : 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'}#獲取頁面數(shù)據(jù)content = requests.post(url=url,headers=headers).text爬取整個(gè)頁面數(shù)據(jù)之后再來看,標(biāo)題和對(duì)應(yīng)的URL在那個(gè)標(biāo)簽中
既然知道了層級(jí)關(guān)系,就行先來解析出標(biāo)題:
import requests from bs4 import BeautifulSoupif __name__ == '__main__':#URLurl = 'http://shicimingju.com/book/sanguoyanyi.html'#UA偽裝headers = {'User-Agent' : 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'}#獲取頁面數(shù)據(jù)content = requests.post(url=url,headers=headers).text#實(shí)例化對(duì)象soup = BeautifulSoup(content,'lxml')# print(soup)#解析文章標(biāo)題和標(biāo)題對(duì)應(yīng)的urlli_list = soup.select('.book-mulu > ul > li')for li in li_list:title = li.a.string#拼接成完整的urltitle_url = 'http://shicimingju.com'+li.a['href']print(title)print(title_url)運(yùn)行結(jié)果:
接下來觀察詳情頁的標(biāo)簽
發(fā)現(xiàn)內(nèi)容全部在p標(biāo)簽下,那我們是不是提取出所有p標(biāo)簽再進(jìn)行處理一下就可以了
每一個(gè)章節(jié)爬取的url在這里就要用的了,在每個(gè)章節(jié)詳情頁再重新實(shí)例化一個(gè)對(duì)象,使用循環(huán)即可爬出所有章節(jié)內(nèi)容
import requests from bs4 import BeautifulSoupif __name__ == '__main__':#URLurl = 'http://shicimingju.com/book/sanguoyanyi.html'#UA偽裝headers = {'User-Agent' : 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'}#獲取頁面數(shù)據(jù)content = requests.post(url=url,headers=headers).text#實(shí)例化對(duì)象soup = BeautifulSoup(content,'lxml')# print(soup)#解析文章標(biāo)題和標(biāo)題對(duì)應(yīng)的urlli_list = soup.select('.book-mulu > ul > li')fp = open('sanguo.txt','w',encoding='utf-8')for li in li_list:title = li.a.stringtitle_url = 'http://shicimingju.com'+li.a['href']# print(title)# print(title_url)#對(duì)詳情頁發(fā)起請(qǐng)求,解析內(nèi)容details_text = requests.get(url=title_url,headers=headers).text#解析內(nèi)容detail_soup = BeautifulSoup(details_text,'lxml')detail_text = detail_soup.find('div',class_='chapter_content')contents = detail_text.textfp.write(title +':'+ contents+ '\n')print(title+':爬取成功')
爬取成功!
總結(jié):
哇 這爬蟲真的越學(xué)習(xí)越有意思,下次學(xué)習(xí)數(shù)據(jù)解析中的xpath
總結(jié)
以上是生活随笔為你收集整理的Python爬虫之旅_(数据解析)_bs4的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 初识反弹Shell
- 下一篇: Python爬虫之旅_(数据解析)_Xp