笔趣看小说Python3爬虫抓取

获取HTML信息

# -*- coding:UTF-8 -*-
import requests if __name__ == '__main__':
target = 'http://www.biqukan.com/1_1094/5403177.html'
req = requests.get(url=target)
print(req.text)

解析HTML信息

提取的方法有很多,例如使用正则表达式、Xpath、Beautiful Soup等。

Beautiful Soup的安装方法和requests一样,使用如下指令安装(也是二选一):

  • pip install beautifulsoup4
  • easy_install beautifulsoup4

仔细观察目标网站一番,我们会发现这样一个事实:class属性为showtxt的div标签,独一份!这个标签里面存放的内容,是我们关心的正文部分。

知道这个信息,我们就可以使用Beautiful Soup提取我们想要的内容了,编写代码如下:

# -*- coding:UTF-8 -*-
from bs4 import BeautifulSoup
import requests
if __name__ == "__main__":
target = 'http://www.biqukan.com/1_1094/5403177.html'
req = requests.get(url = target)
html = req.text
bf = BeautifulSoup(html)
texts = bf.find_all('div', class_ = 'showtxt') print(texts)

在解析html之前,我们需要创建一个Beautiful Soup对象。BeautifulSoup函数里的参数就是我们已经获得的html信息。然后我们使用find_all方法,获得html信息中所有class属性为showtxt的div标签。find_all方法的第一个参数是获取的标签名,第二个参数class_是标签的属性,为什么不是class,而带了一个下划线呢?因为python中class是关键字,为了防止冲突,这里使用class_表示标签的class属性,class_后面跟着的showtxt就是属性值了。看下我们要匹配的标签格式:

<div id="content", class="showtxt">

div标签名,br标签,以及各种空格。怎么去除这些东西呢?

# -*- coding:UTF-8 -*-
from bs4 import BeautifulSoup
import requests
if __name__ == "__main__":
target = 'http://www.biqukan.com/1_1094/5403177.html'
req = requests.get(url = target) html = req.text
bf = BeautifulSoup(html)
texts = bf.find_all('div', class_ = 'showtxt')
print(texts[0].text.replace('\xa0'*8,'\n\n'))

find_all匹配的返回的结果是一个列表。提取匹配结果后,使用text属性,提取文本内容,滤除br标签。随后使用replace方法,剔除空格,替换为回车进行分段。 在html中是用来表示空格的。replace(‘\xa0’*8,’\n\n’)就是去掉下图的八个空格符号,并用回车代替:

小说每章的链接放在了class属性为listmain的<div>标签下的<a>标签中。链接具体位置放在html->body->div->dl->dd->a的href属性中。先匹配class属性为listmain的<div>标签,再匹配<a>标签。编写代码如下:

# -*- coding:UTF-8 -*-
from bs4 import BeautifulSoup
import requests
if __name__ == "__main__":
target = 'http://www.biqukan.com/1_1094/'
req = requests.get(url = target)
html = req.text
div_bf = BeautifulSoup(html)
div = div_bf.find_all('div', class_ = 'listmain')
print(div[0])

下来再匹配每一个<a>标签,并提取章节名和章节文章。

Beautiful Soup返回的匹配结果a,使用a.get(‘href’)方法就能获取href的属性值,使用a.string就能获取章节名,编写代码如下:

# -*- coding:UTF-8 -*-
from bs4 import BeautifulSoup
import requests
if __name__ == "__main__":
server = 'http://www.biqukan.com/'
target = 'http://www.biqukan.com/1_1094/'
req = requests.get(url = target) html = req.text
div_bf = BeautifulSoup(html)
div = div_bf.find_all('div', class_ = 'listmain')
a_bf = BeautifulSoup(str(div[0]))
a = a_bf.find_all('a')
for each in a:
print(each.string, server + each.get('href'))

因为find_all返回的是一个列表,里边存放了很多的<a>标签,所以使用for循环遍历每个<a>标签并打印出来。

整合代码

整合代码,将获得内容写入文本文件存储就好了。

# -*- coding:UTF-8 -*-
from bs4 import BeautifulSoup
import requests, sys class downloader(object): def __init__(self):
self.server = 'http://www.biqukan.com/'
self.target = 'http://www.biqukan.com/1_1094/'
self.names = [] #存放章节名
self.urls = [] #存放章节链接
self.nums = 0 #章节数 def get_download_url(self):
req = requests.get(url = self.target)
html = req.text
div_bf = BeautifulSoup(html)
div = div_bf.find_all('div', class_ = 'listmain')
a_bf = BeautifulSoup(str(div[0]))
a = a_bf.find_all('a')
self.nums = len(a[15:]) #剔除不必要的章节,并统计章节数
for each in a[15:]:
self.names.append(each.string)
self.urls.append(self.server + each.get('href')) def get_contents(self, target):
req = requests.get(url = target)
html = req.text
bf = BeautifulSoup(html)
texts = bf.find_all('div', class_ = 'showtxt')
texts = texts[0].text.replace('\xa0'*8,'\n\n')
return texts """
函数说明:将爬取的文章内容写入文件
Parameters:
name - 章节名称(string)
path - 当前路径下,小说保存名称(string)
text - 章节内容(string)
Returns:

"""
def writer(self, name, path, text):
write_flag = True
with open(path, 'a', encoding='utf-8') as f:
f.write(name + '\n')
f.writelines(text)
f.write('\n\n') if __name__ == "__main__":
dl = downloader()
dl.get_download_url()
print('《一念永恒》开始下载:')
for i in range(dl.nums):
dl.writer(dl.names[i], '一念永恒.txt', dl.get_contents(dl.urls[i]))
sys.stdout.write(" 已下载:%.3f%%" % float(i/dl.nums) + '\r')
sys.stdout.flush()
print('《一念永恒》下载完成')

最新文章

  1. JS正则表达式元字符
  2. (C++)窗口置前SetForegroundWindow(pThis-&gt;hwndWindow);
  3. Google Protocol Buffer 的使用和原理[转]
  4. hadoop: hbase1.0.1.1 伪分布安装
  5. 华硕X84L无线驱动查找
  6. 基于CSS3制作的鼠标悬停动画菜单
  7. Insert into a Cyclic Sorted List
  8. sql数据库链接
  9. 微信小程序如何导入字体图标
  10. mysql遇到的问题:can&#39;t creat/write to file &quot;/var/mysql/xxxx.MYI&quot;
  11. POJ3071 Football 概率DP 简单
  12. Loj10086 Easy SSSP
  13. 洛谷P2196 挖地雷(dp)
  14. django2自动发现项目中的url
  15. 平衡搜索树--红黑树 RBTree
  16. PIE SDK栅格生成等值线、面
  17. 手机移动端 web整合
  18. MySql 自适应哈希索引
  19. HTML-Table-Td固定宽度使内容换行
  20. 【leetcode 239. 滑动窗口最大值】解题报告

热门文章

  1. Socket粘包问题的3种解决方案,最后一种最完美!
  2. mysql远程访问被拒绝问题
  3. Docker-MsSqlServer和安装版本异同
  4. 杭电2734----Quicksum(C++)(数字与字符的关系)
  5. [每日一题]面试官问:谈谈你对ES6的proxy的理解?
  6. Java 使用拦截器无限转发/重定向无限循环/重定向次数过多报错(StackOverflowError) 解决方案
  7. 内存性能测试 Memtester+mbw
  8. 【MySQL】DDL数据定义语言的基本用法create、drop和alter(增删改)
  9. 【MySQL】MySQL知识图谱
  10. 【ORA】ORA-01078和LRM-00109 解决方法