用Python3寫乙個簡單的爬小說的爬蟲(上)

2021-09-25 19:04:16 字數 1836 閱讀 4349

import requests

import re

url = ''

#模擬瀏覽器傳送http請求

response = requests.get(url)

#網頁原始碼

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寫乙個簡單的爬**的爬蟲(下)

用Python3寫乙個簡單的爬小說的爬蟲(下)

import requests import re from bs4 import beautifulsoup 獲取整個頁面,筆趣閣某本 的 url response requests.get url html response.text 清洗資料 title re.findall html,re....

用python寫乙個簡單的視窗

import sys if name main 建立乙個視窗 w qwidget 設定視窗的尺寸 w.resize 400,200 移動視窗 w.move 300,300 設定視窗的標題 w.setwindowtitle 第乙個基於pyqt5的桌面應用 顯示視窗 w.show 進入程式的主迴圈 並通...

ROS 用Python寫乙個簡單服務

一.編寫服務資料 在功能包的頂級目錄中,建立srv資料夾,並在裡面建立.srv檔案 先成為a.srv 在srv檔案中,填入服務資料,如 int64 a int64 b int64 sum其中,上方是請求資料,下方是答應資料 二.修改cmakelist和package.xml cmakelist ca...