用python爬取小说章节内容

在学爬虫之前, 最好有一些html基础, 才能更好的分析网页. 

主要是五步:

1.  获取链接

2. 正则匹配

3. 获取内容

4. 处理内容

5. 写入文件

代码如下:

 1 #导入相关model
 2 from bs4 import BeautifulSoup
 3 import requests
 4 import re
 5 
 6 #获取目标链接地址
 7 url = 'http://www.biquyun.com/0_292/'
 8 reponse = requests.get(url)
 9 reponse.encoding = 'gbk' #设置编码方式,可在网页源码头部查到
10 html = reponse.text
11 
12 #获取各章节链接和标题
13 #审查元素, 找到小说章节的代码位置, 找出其对应的标签, 进行正则匹配
14 dl = re.findall(r'<dd><a href="(.*?)">(.*?)</a>', html, re.S) #返回list类型
15 j=0 #计数, 只获取前30章, 多了结果要很久才出来
16 
17 #进行章节内容获取
18 for chapter in dl:
19     if j >= 30:
20         break
21     #获取章节链接,名字.等价于c_link=chapter[0]; c_title=chapter[1]
22     chapter_link, chapter_title = chapter
23     #补全链接,因为之前获取的只是链接的尾部
24     chapter_link = "http://www.biquyun.com%s" % chapter_link
25 
26     #仿照之前的再写一遍
27     chapter_reponse = requests.get(chapter_link)
28     chapter_reponse.encoding='gbk'
29     chtml = chapter_reponse.text
30     #找到小说章节正文所在标签
31     chapter_content = re.findall(r'<div id="content">(.*?)</div>', chtml,re.S)
32     #将它们转换为字符串,因为list无法进行replace操作
33     t = str(chapter_title)
34     s = str(chapter_content)
35     #替代好空格,换行, 以及列表的左右中括号
36     s = s.replace('&nbsp;','').replace('<br />',"\n").replace('\\r\\n','')
37     s = s.replace(']',"\n").replace('[',' ').replace
38     #新建txt文件,并将其名字设置为章节名, 写入
39     f = open('E:/temp/zhuxian/%s.txt' % chapter_title, 'w')
40     f.write(t)
41     f.write('\n')
42     f.write(s)
43     j = j+1
44 print('ok')
45 f.close()
46 ''' s = s.replace('[','')
47     s = s.replace('<br />',"\n")
48     s = s.replace('\\r\\n','')'''

猜你喜欢

转载自www.cnblogs.com/DSYR/p/10320104.html