最近,我像爬取一下三国演义这本书籍的全部内容。
网站的网址为:https://www.shicimingju.com/book/sanguoyanyi.html
但是我爬取出来的结果是这样的
会遇到乱码。
经过我多方面的调试发现,就是网页的编码和我pycharm的编码不一致导致的。
网页的编码是ISO-8859-1,而pycharm的编码是‘utf-8’
# encode编码,将ISO-8859-1编成unicode
page_text = page_text.encode('ISO-8859-1')
# decode解码,将unicode解码成utf-8
page_text = page_text.decode('utf-8')
通过重新编码和解码来达到网页和编译器的编码一致。
修改前的代码:
# -*- coding: utf-8 -*-
# @Time : 2024/1/24 20:16
# @File : 04. bs4案例.py
# @Description : None
# ----------------------------------------------
# ☆ ☆ ☆ ☆ ☆ ☆ ☆
# >>> Author : Kinght_123
# >>> Mail : 1304662247@qq.com
# >>> Blog : tim1304662247.blog.csdn.net
# ☆ ☆ ☆ ☆ ☆ ☆ ☆
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/120.0.0.0 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')
print(li_list)
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(title + ':' + content + '\n')
print(title, '爬取成功!!!')
修改后的代码:
# -*- coding: utf-8 -*-
# @Time : 2024/1/24 20:16
# @File : 04. bs4案例.py
# @Description : None
# ----------------------------------------------
# ☆ ☆ ☆ ☆ ☆ ☆ ☆
# >>> Author : Kinght_123
# >>> Mail : 1304662247@qq.com
# >>> Blog : tim1304662247.blog.csdn.net
# ☆ ☆ ☆ ☆ ☆ ☆ ☆
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/120.0.0.0 Safari/537.36'
}
url = 'https://www.shicimingju.com/book/sanguoyanyi.html'
page_text = requests.get(url=url, headers=headers).text
# encode编码,将ISO-8859-1编成unicode
page_text = page_text.encode('ISO-8859-1')
# decode解码,将unicode解码成utf-8
page_text = page_text.decode('utf-8')
# 在首页中解析出章节的标题和详情页的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 = 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(title + ':' + content + '\n')
print(title, '爬取成功!!!')
最终显示的结果是这样的: