小编给大家分享一下如何使用BeautifulSoup4数据解析实例,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!这里以爬取三国演义所有章节为例。1.爬取要求是爬取
小编给大家分享一下如何使用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数据解析实例”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注编程网精选频道!
--结束END--
本文标题: 如何使用BeautifulSoup4数据解析实例
本文链接: https://lsjlt.com/news/272670.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0