爬虫日记-笔趣阁小说爬取

温习一下

爬虫所需软件包及用法

import requests
from bs4 import BeautifulSoup
import pprint
import json
import pandas as pd
import re

requests: 这是一个用于发送HTTP请求的Python库,它使访问网页、下载数据变得非常简单。在爬虫中,requests.get() 方法经常被用来从网页服务器获取HTML内容。

import requests
response = requests.get('http://example.com')
content = response.text

BeautifulSoup: 这是一个用于解析HTML和XML文档的库,常与requests一起使用。它可以帮助从网页源代码中提取有用的信息,如标题、链接、文本内容等。

from bs4 import BeautifulSoup
soup = BeautifulSoup(content, 'html.parser')
title = soup.find('title').text

pprint: 这是Python自带的模块,用于打印数据结构(如字典、列表)的美化版本,使其更易阅读。

import pprint
pprint.pprint(some_data_structure)

json: Python内置的JSON处理模块,可以将字典等数据转换为JSON字符串,或者将JSON字符串转换为Python数据结构,方便数据交换和存储。

import json
data = {'key': 'value'}
json_str = json.dumps(data)
loaded_json = json.loads(json_str)

pandas: 是一个强大的数据分析和操作库,提供了DataFrame这样的二维表格数据结构,非常适合处理和分析大量数据。

import pandas as pd
df = pd.read_csv('data.csv')
filtered_df = df[df['column_name'] == 'some_value']

re: Python的标准正则表达式库,用于匹配或提取文本中的模式。

import re
pattern = re.compile(r'\d+')
matches = pattern.findall('There are 123 apples and 456 oranges.')

爬取目标小说网站

在这里插入图片描述

爬虫代码

import requests
from bs4 import BeautifulSoup
import pprint
import json
import pandas as pd
import re
"""
data.append 是一个在编程中常见的操作,尤其是在使用列表(list)数据结构时。这里的 data 是一个列表变量的名称,而 .append 是列表对象的一个方法。当你调用 data.append(item) 时,意味着你正在向列表 data 的末尾添加一个元素 item。
"""
"""
对于每个找到的链接link,提取它的href属性值,将其与给定的基础URL拼接成完整的URL,同时获取该链接的文本描述(即用户可见的链接文字),然后将这对信息作为元组加入到data列表中。不过,原始代码中的百分号用法不符合Python的字符串格式化规范,所以需要修正。
"""
head=headers={'User-Agent': 'Mozilla/5.0'}
def get_novel():
    root_url="https://www.bigee.cc/book/68826/"
    r=requests.get(root_url,headers=head)
    r.encoding="utf-8"
    soup=BeautifulSoup(r.text,"html.parser")
    data=[]
    for dd in soup.find_all("dd"):
        link = dd.find("a")
        if link:
            href = link.get('href')
            # 确保链接是有效页面链接,这里以判断是否以 '.html' 结尾为例
            if href.endswith('.html'):
                full_url = "https://www.bigee.cc" + href
                title = link.get_text()
                data.append((full_url, title))
    return data
#get_novel()
def get_chapter_content(url):
    r=requests.get(url,headers=head)
    r.encoding="utf-8"
    soup = BeautifulSoup(r.text, "html.parser")
    return (soup.find("div",id='chaptercontent').get_text())


novel=get_novel()
total_cnt=len(novel)
idx=0

for chapter in get_novel():
    idx +=1
    print(idx,total_cnt)
    url,title = chapter
    safe_title = re.sub(r'[<>:"/\\|?*]', '', title)  # 移除非法字符
    safe_title = safe_title.strip()  # 移除首尾空白
    file_name = f"{safe_title}.txt"
    with open(file_name,"w",encoding="utf-8")as fout:
        fout.write(get_chapter_content(url))







结果以txt形式输出

源码下载

资源
解压后源码在novel文件夹里craw.py

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

净网平台

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

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

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

打赏作者

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

抵扣说明:

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

余额充值