用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','')'''

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM