Python爬取笔趣阁小说,有趣又实用
点击上方Python知识圈,设为星标
回复100获取100题PDF
阅读文本大概需要 5 分钟
1. 首先导入相关的模块
import osimport requestsfrom bs4 import BeautifulSoup
2. 向网站发送请求并获取网站数据
# 声明请求头headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36'}# 创建保存小说文本的文件夹if not os.path.exists('./小说'):os.mkdir('./小说/')# 访问网站并获取页面数据response = requests.get('http://www.biquw.com/book/1/').textprint(response)
这是因为页面html的编码格式与我们python访问并拿到数据的解码格式不一致导致的,python默认的解码方式为utf-8,但是页面编码可能是GBK或者是GB2312等,所以我们需要让python代码很具页面的解码方式自动变化
#### 重新编写访问代码```pythonresponse = requests.get('http://www.biquw.com/book/1/')response.encoding = response.apparent_encodingprint(response.text)'''这种方式返回的中文数据才是正确的'''
3. 拿到页面数据之后对数据进行提取

'''根据上图所示,数据是保存在a标签当中的。a的父标签为li,li的父标签为ul标签,ul标签之上为div标签。所以如果想要获取整个页面的小说章节数据,那么需要先获取div标签。并且div标签中包含了class属性,我们可以通过class属性获取指定的div标签,详情看代码~'''# lxml: html解析库 将html代码转成python对象,python可以对html代码进行控制soup = BeautifulSoup(response.text, 'lxml')book_list = soup.find('div', class_='book_list').find_all('a')# soup对象获取批量数据后返回的是一个列表,我们可以对列表进行迭代提取for book in book_list:book_name = book.text# 获取到列表数据之后,需要获取文章详情页的链接,链接在a标签的href属性中book_url = book['href']
4. 获取到小说详情页链接之后进行详情页二次访问并获取文章数据
book_info_html = requests.get('http://www.biquw.com/book/1/' + book_url, headers=headers)book_info_html.encoding = book_info_html.apparent_encodingsoup = BeautifulSoup(book_info_html.text, 'lxml')
5. 对小说详情页进行静态页面分析
info = soup.find('div', id='htmlContent')print(info.text)
6. 数据下载
with open('./小说/' + book_name + '.txt', 'a', encoding='utf-8') as f:f.write(info.text)
最后让我们看一下代码效果吧~
抓取的数据
往期推荐 01 02 03 
↓点击阅读原文查看pk哥原创视频
   
    
     
      
       
        我就知道你“在看”
        
       
      
       
        
        
       
      
     
    
 
 
       评论





