爬取笔趣阁玄幻-元尊小说内容

本文介绍了如何使用Python的requests和lxml库进行网页爬取,获取小说网站的章节链接,然后解析HTML内容提取书名、作者和章节内容,保存到文本文件中。注意需处理编码问题并定期更换User-Agent以避免被封禁。
摘要由CSDN通过智能技术生成

import requests
from lxml import etree

headers = {'User-Agent':
                               'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36',
                           }

def get_response(html_url):
    response = requests.get(url=html_url,headers=headers)
    return response
# https://www.beqege.com/1076/14341.html
def get_novel_url(html_url):
    response = get_response(html_url)
    response.encoding='utg-8'
    tree = etree.HTML(response.text)
    href_list = tree.xpath('//div[@id="list"]//dd//a//@href')
    href = ['https://www.beqege.com'+i for i in href_list]
    return href


def save(name,title,content):
    with open(name+'.txt','a',encoding='utf-8') as f:
        f.write(title)
        f.write('\n')
        f.write(content)
        f.write('\n')
def get_novel_content(novel_url):
    response = get_response(novel_url)
    response.encoding = 'utg-8'(注意编码格式可能会有问题,用response.encoding=response.apparent_encoding改变编码)
    tree = etree.HTML(response.text)
    name_list = tree.xpath('//div[@class="con_top"]//a[3]//text()')
    title_list = tree.xpath('//div[@class="bookname"]//text()')
    content_list = tree.xpath('//div[@id="content"]//text()')
    # 列表转化为字符串
    name = name_list[0]
    title = title_list[0]
    content = ''.join(content_list)
    save(name,title,content)

 

if __name__ == '__main__':
    url = 'https://www.beqege.com/1076/'
    href = get_novel_url(url)
    for index in href:
        get_novel_content(index)

 

 

注意:换一个headers,就可以了,但是爬久了,会被禁止访问,可以去买一个ip 试试看。亲测有效。

注意的事项:

需要加一句语句:response.encoding=response.apparent_encoding

 

  • 16
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

努力学习各种软件

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值