![](https://img.haomeiwen.com/i3968643/0c945f89c13af617.png)
image.png
![](https://img.haomeiwen.com/i3968643/44c8217d392f49d1.png)
image.png
![](https://img.haomeiwen.com/i3968643/4e3e08520717ab93.png)
image.png
![](https://img.haomeiwen.com/i3968643/45b8f403eeade618.png)
image.png
![](https://img.haomeiwen.com/i3968643/bd958cf90c68eea6.png)
image.png
from bs4 import BeautifulSoup
if __name__=="__main__":
fp = open('./test.html','r',encoding='utf-8')
soup = BeautifulSoup(fp,'lxml')
print(soup)
![](https://img.haomeiwen.com/i3968643/9daa3e90404506fb.png)
image.png
![](https://img.haomeiwen.com/i3968643/4e98790a073c44ba.png)
image.png
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 爬取三国演义所有章节标题和章节内容
import requests
from bs4 import BeautifulSoup
if __name__=="__main__":
# 对首页的页面数据进行爬取
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/96.0.4664.45 Safari/537.36'
}
url = 'https://www.shicimingju.com/book/sanguoyanyi.html'
page_text = requests.get(url=url,headers=headers).text
# 在首页中解析出章节的标题和详情页的url
#1. 实例化BeautifulSoup对象,需要将页面源码数据加载到该对象中
soup = BeautifulSoup(page_text,'lxml') # 此处解析的是首页内容
# 解析章节标题和详情页的url
li_list = soup.select('.book-mulu > ul > li')
fp = open('./sanguo.txt','w',encoding='utf-8')
for li in li_list:
title = str(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')
# print(detail_soup)
div_tag = detail_soup.find('div',class_='chapter_content')
# 解析到了章节的内容
content = div_tag.text
fp.write(title+':'+ content + '\n')
print(title + '爬取成功!!!')
网友评论