一、什么是爬虫
网络爬虫,也称作网络蜘蛛、网页追逐者或自动索引器,是一种能自动从互联网上按照一定规则抓取信息的程序或脚本。这些信息可以是公开的网页内容,例如文本、图片、音视频等各类数据。随着大数据时代的到来,网络爬虫在许多领域都有重要应用,如搜索引擎、数据分析与挖掘、金融分析、舆情监测等。
二、基于正则表达式实现爬虫
正则表达式是一种由特定字符和特殊操作符组成的模式描述,用于在文本中查找、替换、提取和验证符合特定模式的字符串。
符号 | 描述 |
---|---|
. |
匹配任意单个字符(除了换行符) |
* |
匹配前面的子表达式零次或多次 |
+ |
匹配前面的子表达式一次或多次 |
? |
匹配前面的子表达式零次或一次 |
{n} |
匹配前面的子表达式恰好 n 次 |
{n,} |
匹配前面的子表达式至少 n 次 |
{n,m} |
匹配前面的子表达式至少 n 次,但不超过 m 次 |
^ |
匹配输入字符串的开始位置 |
$ |
匹配输入字符串的结束位置 |
\d |
匹配一个数字字符。等价于 [0-9] |
\D |
匹配一个非数字字符。等价于 [^0-9] |
\w |
匹配任何单词字符(字母、数字或下划线)。等价于 [a-zA-Z0-9_] |
\W |
匹配任何非单词字符。等价于 [^a-zA-Z0-9_] |
\s |
匹配任何空白字符(空格、制表符、换页符等)。等价于 `[\f |
\S |
匹配任何非空白字符。等价于 `[^\f |
[...] |
定义一个字符集合,匹配方括号内的任意字符。例如,[abc] 匹配 "a"、"b" 或 "c"。 |
[^...] |
定义一个反向字符集合,匹配不在方括号内的任意字符。例如,[^abc] 匹配除 "a"、"b" 和 "c" 之外的任何字符。 |
(pattern) |
标记一个子表达式的开始和结束位置。子表达式可以获取供以后使用。 |
() |
分组符号,将几个字符当作一个整体进行处理。 |
\ |
转义字符,用于匹配特殊字符(如 * , + , ? , { , } 等)。 |
查找页面中的所有连接<a>标签的href内容
#查找页面所有超链接
import re
import requests
resp = requests.get('https://www.bqgui.cc/')
#print(resp.text)
links =re.findall('<a href=''(.+?)''>',resp.text)
for link in links:
print(link)
拼接url并下载页面
import re, requests, time
resp = requests.get('https://www.bqgui.cc/')
links = re.findall('<a href=''(.+?)''>', resp.text)
for link in links:
# 先根据页面特性,将一些无用的超链接进行排除
if '.html' in link:
continue
if link.startswith('#'):
continue
# 对超链接进行处理,拼接出完整的URL地址
if link.startswith('/'):
link = 'https://www.bqgui.cc' + link.strip('"')
# 将页面文件保存于本地
resp = requests.get(link)
resp.encoding = 'utf-8'
filename = link.split('/')[-1] + time.strftime("%Y%m%d_%H%M%S") + '.html'
with open(f'/{filename}', mode='w', encoding='utf-8') as file:
file.write(resp.text)
三、基于BeautifulSoup实现爬虫笔趣阁小说
BeautifulSoup是一个Python库,用于解析HTML和XML文档,可以用来提取数据。要使用BeautifulSoup,首先需要安装它。可以使用以下命令进行安装:pip install beautifulsoup4
beautifulsoup的基本操作:
from bs4 import BeautifulSoup
import requests
resp = requests.get('https://www.bqgui.cc/')
#初始化解析器
html = BeautifulSoup(resp.text, 'lxml')
#查找页面元素(根据标签层次进行查找)
print(html.head.title) # 根据标签的层次找页面标题
print(html.head.title.string) # 获取页面标题的文本内容
print(html.div) # 查找页面中的第一个DIV元素
#查找页面元素的通用方法:
#1、find_all:根据标签,属性,XPath等进行查找
#2、select:CSS选择器,div,id,class
#查找页面所有超链接
links = html.find_all('a')
for link in links:
print(link['href'])
#查找页面的图片
images = html.find_all('img')
for image in images:
print(image['src'])
#根据id或class篇属性查找
keyword = html.find(id='keyword')
print(keyword)
#print(keyword['placeholder'])
titles = html.find_all(class_='title')
for title in titles:
print(title)
print(title.string)
print(title.find('a'))
#print(title.find('a').string)
print('===========================')
title = html.find(text='混沌')
#print(title.parent)
#print(title.parent.parent)
print('===============================')
# 根据xpath的风格进行查找 //div[@class='title']
titles = html.find_all('div',{'class':'title'})
for title in titles:
print(title.string)
for title in titles:
print(title.string)
keyword = html.select('#keyword')
print(keyword[0]['placeholder'])
lis = html.select('ul li')
print(lis)
爬取笔趣阁小说:
from bs4 import BeautifulSoup
import requests
#输入url,第几章到第几章,start,end
def download_book(url,start,end):
for i in range(start,end):
#https://www.bqgui.cc/book/182219/
link = f'{url}' + f'{i}.html'
print(link)
# print(link)
resp = requests.get(link)
html = BeautifulSoup(resp.text,'lxml')
context_list = html.select('#chaptercontent')
title = html.select('title')[0].text.strip(',笔趣阁')
#print(title)
with open (f'./{title}.txt',mode='w',encoding='gbk') as f:
f.write(context_list[0].text)
#输入需要爬取的小说名字
def find_book(book_name):
resp = requests.get('https://www.bqgui.cc/finish/')
#print(resp.text)
html = BeautifulSoup(resp.text,'lxml')
book_list = html.select('div dt a')
for book in book_list:
# print(book['href'])
# print(book.text)
if book_name in f'{book.text}':
return 'https://www.bqgui.cc'+book['href']
url = find_book('混沌')
download_book(url,1,10)
每篇一言:如果你在看,我就是你的风景。如果你在听,我该有多幸运。