Python爬取笔趣阁小说(新手可入~)

一个简单的爬取,完整代码放在最后~~~

笔趣阁网址:https://www.biqg.cc/

首先导入需要的库

import requests
import re
from bs4 import BeautifulSoup
import time

点击第一篇文章,按F12进入开发者模式

选择NetWork找到代理服务器

将网址和代理填进去

# 设置代理服务器
    headers = {
        'User_Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'
    }
# 请求网址
url = 'https://www.biqg.cc/book/6909/1.html'
response = requests.get(url, headers=headers)

为了防止文字乱码,还要对其进行转化格式

# 转化为utf-8格式,不加这条语句,输出爬取的信息为乱码
response.encoding = 'utf-8'

使用Beautiful Soup解析网页代码

#获取到源码
html = response.text
#使用Beautiful Soup解析网页内容
soup = BeautifulSoup(html, 'html.parser')

找到标题

使用正则表达式提取标题:

# 正则表达式解析小说章节标题
pattern1 = re.compile(r'<h1 class="wap_none">(.*?)</h1>')
title = re.findall(pattern1, html)

找到小说内容

这里我们用Beautiful Soup来提取

#解析小说章节正文内容
text = soup.find('div', id='chaptercontent').text

打印输出

print(title)
print(text)

第一章提取完成!!!

接下来可以多提取几章,注意观察网址的变化:

因此对网址加个for循环就可以提取多章小说了

for page in range(11):  # 爬取10章小说
    # 请求网址
    url = 'https://www.biqg.cc/book/6909/'+str(page)+'.html'
    time.sleep(1)  # 防止操作过快,网站防爬

最后将内容写入文本文件

with open('novel.txt', 'a', encoding='utf-8') as file:
    file.write('\n'.join(title))
    file.write('\n')
    file.write(text)
    file.write('\n\n')

完整代码如下:

import requests
import re
from bs4 import BeautifulSoup
import time

for page in range(11):  # 爬取10章小说
    # 请求网址
    url = 'https://www.biqg.cc/book/6909/'+str(page)+'.html'
    time.sleep(1)  # 防止操作过快,网站防爬
# 设置代理服务器
    headers = {
        'User_Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'
    }
    response = requests.get(url, headers=headers)
    if response.status_code == 200:   #状态码200表示请求成功
        # 转化为utf-8格式,不加这条语句,输出爬取的信息为乱码
        response.encoding = 'utf-8'
        #获取到源码
        html = response.text
        #使用Beautiful Soup解析网页内容
        soup = BeautifulSoup(html, 'html.parser')
        # 正则表达式解析小说章节标题
        pattern1 = re.compile(r'<h1 class="wap_none">(.*?)</h1>')
        title = re.findall(pattern1, html)
        #解析小说章节正文内容
        text = soup.find('div', id='chaptercontent').text
        # 打印输出
        print(title)
        print(text)
# 写入txt文件
        with open('novel.txt', 'a', encoding='utf-8') as file:
            file.write('\n'.join(title))
            file.write('\n')
            file.write(text)
            file.write('\n\n')

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值