用python爬取小說章節內容

2021-09-10 05:04:44 字數 1610 閱讀 7960

在學爬蟲之前, 最好有一些html基礎, 才能更好的分析網頁. 

主要是五步:

1.  獲取鏈結

2. 正則匹配

3. 獲取內容

4. 處理內容

5. 寫入檔案

**如下:

#匯入相關model

from bs4 import beautifulsoup

import requests

import re

#獲取目標鏈結位址

url = ''

reponse = requests.get(url)

reponse.encoding = 'gbk' #設定編碼方式,可在網頁原始碼頭部查到

html = reponse.text

#獲取各章節鏈結和標題

#審查元素, 找到**章節的**位置, 找出其對應的標籤, 進行正則匹配

dl = re.findall(r'(.*?)', html, re.s) #返回list型別

j=0 #計數, 只獲取前30章, 多了結果要很久才出來

#進行章節內容獲取

for chapter in dl:

if j >= 30:

break

#獲取章節鏈結,名字.等價於c_link=chapter[0]; c_title=chapter[1]

chapter_link, chapter_title = chapter

#補全鏈結,因為之前獲取的只是鏈結的尾部

chapter_link = "" % chapter_link

#仿照之前的再寫一遍

chapter_reponse = requests.get(chapter_link)

chapter_reponse.encoding='gbk'

chtml = chapter_reponse.text

#找到**章節正文所在標籤

chapter_content = re.findall(r'(.*?)

', chtml,re.s)

#將它們轉換為字串,因為list無法進行replace操作

t = str(chapter_title)

s = str(chapter_content)

#替代好空格,換行, 以及列表的左右中括號

s = s.replace(' ','').replace('

',"\n").replace('\\r\\n','')

s = s.replace(']',"\n").replace('[',' ').replace

#新建txt檔案,並將其名字設定為章節名, 寫入

f = open('e:/temp/zhuxian/%s.txt' % chapter_title, 'w')

f.write(t)

f.write('\n')

f.write(s)

j = j+1

print('ok')

f.close()

''' s = s.replace('[','')

s = s.replace('

',"\n")

s = s.replace('\\r\\n','')'''

用python爬取小說章節內容

在學爬蟲之前,最好有一些html基礎,才能更好的分析網頁.主要是五步 1.獲取鏈結 2.正則匹配 3.獲取內容 4.處理內容 5.寫入檔案 如下 匯入相關model 2from bs4 import beautifulsoup 3import requests 4importre5 6 獲取目標鏈結...

Python爬取小說 2 單章節爬取

coding utf 8 urlopen 開啟 request 請求 from urllib.request import urlopen,request 匯入gzip包 解壓gzip 封裝請求 req request url path,headers headers 開啟鏈結 conn urlop...

request爬取小說內容

request爬取 內容 import re import requests import os bookurl 書的位址 booksite requests.get bookurl 獲取書的網頁 booksite.encoding gbk book name re.findall booksite...