一開始按照視頻上的找了筆趣閣的網站先爬一部小說, 找了<遮天>,但是章節太多,爬起來太慢, 就換了一個幾十章的小說.
根據視頻里的去寫了代碼, 在正則表達式哪里出了很大的問題.
from bs4 import BeautifulSoup
import requests
import re先找到了小說主頁的鏈接地址: url = 'https://www.biquge5.com/3_3004/'
reponse = requests.get(url)
reponse.encoding = 'gbk'html = reponse.text
這是網頁的部分代碼
<div id="list"><ul class="_chapter"> <li><a href="https://www.biquge5.com/3_3004/ 1391919.html">第一章 你心里沒點數嗎</a></li><li><a href="https://www.biquge5.com/3_3004/ 1391920.html">第二章 原來是一場精心設計</a></li><li><a href="https://www.biquge5.com/3_3004/ 1391921.html">第三章 你去死啊</a></li><li><a href="https://www.biquge5.com/3_3004/ 1391922.html">第四章 能不能找他借錢</a></li><li><a href="https://www.biquge5.com/3_3004/ 1391923.html">第五章 你一點都不心痛嗎</a></li><li><a href="https://www.biquge5.com/3_3004/ 1391924.html">第六章 在監獄里度過后半生</a></li><li><a href="https://www.biquge5.com/3_3004/ 1391925.html">第七章 我爸媽只生了我一個</a></li><li><a href="https://www.biquge5.com/3_3004/ 1391926.html">第八章 一團迷霧</a></li>寫出正則表達式,找到ul標簽里面的鏈接: dl = re.findall(r'<li><a href="(.*?)">(.*?)<', html, re.S)
結果返回了空列表. 又試了幾種正則表示,還是錯誤的. 檢查了好久也查不出原因.
最后直接打開瀏覽器, 在小說首頁查看源代碼, 復制了href鏈接到搜索欄里, 出現了 404 !
又回到源代碼, 仔細看一下發現href里只有http--3004/有藍色標記,后面的139.....沒有, 於是只復制了前面的http--3004/, 沒想到竟然跳轉到了小說章節內容.
於是又復制了一遍href里的鏈接,發現在瀏覽器搜索框里出現了一個'\n'換行符,把它去點后也可以 正常訪問. 看來就是這個'\n'符就是萬惡之源了.
修改代碼: dl = re.findall(r'<li><a href="https://www.biquge5.com/3_3004/\s(.*?)">(.*?)<' (\s代表可以匹配換行空格等一切字符)
可是還是有問題, 就是在返回的列表里面,鏈接還是有\n.
干脆就把所有的換行符都換掉好了: html = html.replace('\n','')
至此,問題解決了
代碼:
1 from bs4 import BeautifulSoup 2 import requests 3 import re 4 url = 'https://www.biquge5.com/3_3004/' 5 reponse = requests.get(url) 6 reponse.encoding = 'gbk' 7 '''soup = BeautifulSoup(reponse.text, 'lxml') 8 chapter = soup.select('ul._chapter > li > a') 9 temp=[] #鏈接 10 temp2=[] #章節標題''' 11 12 ''' 13 #用字典 14 for c in chapter: 15 temp.append(c.get_text()) 16 temp2.append(c.get('href')) 17 print(temp2)''' 18 '''f = open('遮天.txt','w') 19 for i in temp: 20 f.write(str(i)) 21 f.write('\n') 22 print('ok') 23 f.close()''' 24 '''f = open('遮天.txt','w') 25 for c in chapter: 26 data={ 27 'clink': c.get('href'), 28 'ctitle': c.get_text() 29 } 30 for i in data.values(): 31 f.write(i[1]) 32 print('ok') 33 exit() 34 35 tml = reponse.text 36 html = html.replace('\n','') 37 dl = re.findall(r'<li><a href="https://www.biquge5.com/3_3004/\s(.*?)">(.*?)<', html, re.S) 38 #print((chapter_info_list)) 39 for i in dl: 40 m,n=i 41 m="https://www.biquge5.com/3_3004/\n%s" % m 42 print(m,n) 43 ''' 44 45 46 html = reponse.text 47 html = html.replace('\n','') 48 dl = re.findall(r'<li><a href="https://www.biquge5.com/3_3004/(.*?)">(.*?)<', html, re.S) 49 for i in dl: 50 m,n=i 51 m="https://www.biquge5.com/3_3004/%s" % m #將鏈接前面的東西加到m上, + 的方式效率低,采用占位符%S代替. 52 print(m,n)
結果: