小编给大家分享一下如何使用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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。