#下載一個網頁
import requests
import re
url = 'https://www.biquge5200.cc/14_14621/'
#模擬瀏覽器發送http請求
response = requests.get(url)
#編碼方式response.encoding = 'utf-8',如果下載下來的網頁內容有中文亂碼現象就需要加上這一句話
#網頁源碼
html = response.text
#[0]取列表下第0個元素.
#eg:title的輸出結果為:['斗神狂飆無彈窗_斗神狂飆最新章節列表_斗神狂飆5200_筆趣閣']
#加上[0],就把這里面索引為0的內容提取出來了,斗神狂飆無彈窗_斗神狂飆最新章節列表_斗神狂飆5200_筆趣閣
title = re.findall(r'
', html)[0]
#新建一個文件夾,保存小說內容
fb = open('%s.txt' % title, 'w', encoding='utf-8')
#獲取每一章的信息(標題,章節,url).*? (這個 . 代表匹配任意字符,但是不匹配不可見字符,比如換行)
# 添加上re.S后,意味著 . 可以匹配不可見字符,[0]取列表下第0個元素
dl = re.findall(r'
.*?
', html, re.S)[0]
chapter_info_list = re.findall(r'
(.*?)
', dl)
#循環每一個章節,分別下載
for chapter_info in chapter_info_list:
try:
chapter_title = chapter_info[1]
chapter_url = chapter_info[0]
# 下載章節內容
chapter_response = requests.get(chapter_url)
chapter_html = chapter_response.text
# 取出章節內容,用正則表達式,寫進記事本里
chapter_content = re.findall(r'
(.*?)
', chapter_html, re.S)[0]
#清洗數據,但是replace用不了,未完待續,來個大神救我一下。。。。
#chapter_content = chapter_content.replace(' ','')
# chapter_content = chapter_content.replace('?', '')
# chapter_content = chapter_content.replace('', '')
#下面的代碼也不能用,它給我的每個字都添加了單引號和逗號,不解
#chapter_content = [item.replace(' ', '') for item in chapter_content]
#chapter_content = [item.replace('', '') for item in chapter_content]
#數據持久化
fb.write(chapter_title)
fb.write(chapter_content)
fb.write('\n')
except IndexError:
pass
#bug:list index out of range
#失敗原因:爬蟲在做xpath時候匹配到空值
#解決方法:加上try.....except 錯誤機制跳過dd空值
學習python第二天、、爬蟲第二天、、這個簡單的爬蟲,還有數據清洗那一塊有問題,找個有緣的朋友悄咪咪的tell me 一下?在此萬分感謝!
chapter_content = chapter_content.replace(' ?','')這個問題還是沒有解決,但是我用BeautifulSoup解決了數據清洗!請看用Python3寫一個簡單的爬小說的爬蟲(下)https://blog.csdn.net/LiebeZQ/article/details/98189065
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
