python爬取小说

程序的目的是从网页上爬取小说,我爬取了第一本小说,出现的的问题是,我可以爬取小说的正文部分,但到番外就自动停止了并且出现了bug:UnicodeEncodeError: 'gbk' codec can't encode character luedb7' in position 184: illegal multibyte sequence;
我尝试爬取了第二本小说,正文和番外都爬取成功了;
两本小说在同一个网站,网址url规律是一样的;
我考虑了可能是编码的问题,尝试了几种方法都没有解决,求问还可能是什么问题呢?

爬取小说的代码:


import requests
from bs4 import BeautifulSoup

url = "https://m.bqg456.com/read/61973/list.html"
headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.63"}
response = requests.get(url, headers=headers)
html = response.text
soup = BeautifulSoup(html, "lxml")
content_all = soup.find_all(name="dd")
url_end = content_all[1].find("a").attrs["href"]

while url_end != "/read/61973/":
    secUrl = "https://m.bqg456.com" + url_end
    secResponse = requests.get(secUrl)
    response.encoding = response.apparent_encoding
    secHtml = secResponse.text
    secSoup = BeautifulSoup(secHtml, "lxml")

    secName = secSoup.find(class_="title").text

    secContent_all = secSoup.find_all(id="chaptercontent")
    for secContent in secContent_all:
        sec = secContent.text
        secContent = sec.replace("  ", "\n")
        secContent = secContent.replace(
            "请收藏:https://m.bqg456.com (温馨提示:请关闭畅读或阅读模式,否则内容无法正常显示)", "\n")

    text = secName + secContent

    with open(r"D:\系统默认\桌面\赵浪穿越秦朝1.txt", "a") as f:
            f.write(text)

    secUrl = secSoup.find(class_="Readpage_down js_page_down")
    url_end = secUrl.attrs["href"]

print("success")

根据你的描述,可能是因为在爬取第一本小说时,出现了某些字符无法被GBK编码的问题,导致出现了UnicodeEncodeError异常。而在第二本小说中没有出现这个问题,可能是因为它没有包含那些无法被GBK编码的字符。

你可以尝试使用其他编码方式,例如UTF-8或者GB2312来解决这个问题。具体方法如下:

  • 尝试使用UTF-8编码方式。在你的代码中添加以下行:
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

这将设置标准输出的编码方式为UTF-8。

  • 尝试使用GB2312编码方式。在你的代码中添加以下行:
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='gb2312')

这将设置标准输出的编码方式为GB2312。

如果以上方法都不能解决问题,可能需要对你的代码进行进一步的调试和排查,查看具体哪些字符导致了编码问题,然后再针对性地解决。可以尝试打印出相关的字符,查看它们的编码方式和对应的Unicode码点。

回答如下,记得采纳一下哦!
使用UTF-8吧,小说中有可能会有一些偏僻汉字,UTF-8编码下的汉字比GBK编码下的汉字多。

secResponse = requests.get(secUrl).content  #获取二进制形式数据然后解码

secResponse = secResponse.decode("utf-8")

from requests_html import HTMLSession
import re
url='https://m.bqg456.com/read/61973/list.html'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'}

session  =HTMLSession()
res=session.get(url,headers=headers)
title=res.html.xpath('//*[@class="title"]//text()')[0]
page=int(re.findall(r'\d+',title)[0])+1
for i in range(1,page):
    text=''
    url=f'https://m.bqg456.com/read/61973/{i}.html'
    res=session.get(url,headers=headers)
    data=res.html.xpath('//*[@id="chaptercontent"]//text()')
    for j in data:
        text=f'{text}{j}\n'
    titles=res.html.xpath('//*[@class="title"]//text()')[0]
    title=re.sub(r"1)|\(.*?\)|\(.*?\)|\(.*?\)|_赵浪穿越秦朝", "", titles)
    title.strip()
    num=re.findall('\d+',title)
    if num and int(num[0])<i-1:
        title=f"完结后{title}"
    with open(f"e:/1/{title}.txt", "w",encoding='utf-8') as f:
         f.write(text)

img

在发起请求拿到内容的编码部分加上一个decode(‘gbk’)即可,可以同时使用多个decode