您好,登錄后才能下訂單哦!
小編給大家分享一下如何使用BeautifulSoup4數據解析實例,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
這里以爬取三國演義所有章節為例。
1.爬取要求是爬取三國演義的所有章節
2.目標地址:https://www.shicimingju.com/book/sanguoyanyi.html
3.代碼
from bs4 import BeautifulSoupimport requestsif __name__ == '__main__':headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'}url = 'https://www.shicimingju.com/book/sanguoyanyi.html'page_text = requests.get(url=url,headers=headers).text soup = BeautifulSoup(page_text,'lxml')li_list = soup.select('.book-mulu > ul > li')fp = open('./三國演義小說.txt','w',encoding='utf-8')for li in li_list:title = li.a.string detail_url = 'https://www.shicimingju.com'+li.a['href']detail_page_text = requests.get(url=detail_url,headers=headers).text detail_soup = BeautifulSoup(detail_page_text, 'lxml')div_tag = detail_soup.find('div',class_='chapter_content')content = div_tag.text fp.write('\n' + title + ':' + content +'\n')print(title,'爬取成功')
4.出現亂碼以及處理
response.text在用文本格式看的時候有亂碼,回來的內容可能被壓縮了。在此修改response.content.decode(utf-8)以utf-8格式輸出。
from bs4 import BeautifulSoupimport requestsif __name__ == '__main__':headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'}url = 'https://www.shicimingju.com/book/sanguoyanyi.html'page_text = requests.get(url=url,headers=headers).content.decode("utf-8")soup = BeautifulSoup(page_text,'lxml')li_list = soup.select('.book-mulu > ul > li')fp = open('./三國演義小說.txt','w',encoding='utf-8')for li in li_list:title = li.a.string detail_url = 'https://www.shicimingju.com'+li.a['href']detail_page_text = requests.get(url=detail_url,headers=headers).content.decode("utf-8")detail_soup = BeautifulSoup(detail_page_text, 'lxml')div_tag = detail_soup.find('div',class_='chapter_content')content = div_tag.text fp.write('\n' + title + ':' + content +'\n')print(title,'爬取成功')
5.最終效果展現
以上是“如何使用BeautifulSoup4數據解析實例”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。