温习一下
爬虫所需软件包及用法
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