一个简单的爬取,完整代码放在最后~~~
笔趣阁网址: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')