python爬取小說詳解

2021-08-19 03:35:53 字數 3252 閱讀 6753

爬取的**url為

第一步:geturl 解析

url(用

beautifulsoup

)start_url=""

url=start_url+str(11987333)+'.html'

html=requests.get(url,timeout=15)

soup=beautifulsoup(html.content,'lxml')//這裡用

html.text

也是可以的

易知**內容放在id=『

htmlcontent

』的標籤內

題目放在class=『h1title』

所以尋找所有標籤為id=『

htmlcontent

』或者class=

『h1title

』內的內容

title=soup.find_all('div',class_='h1title')

content=soup.find_all('div',id='htmlcontent')

s=''.join('%s' %id for id in content)//為什麼選擇這樣而不是用

上網查了資料,說

list

包含數字,不能直接轉化成字串。

join資料在這個**

執行後發現還有乙個』

』,第乙個想法是用replace來替換』

』所以執行

s.replace('

','')

print(s)

但是結果卻不是這樣

還是存在

後來發現我是真的蠢

在python中字串是immutable的物件,replace是不會直接變更字串內容的,只會建立乙個新的。需要重新引用將replace返回的替換後的字串結果。

現在那些該死的

終於沒了

發現標題中還有那些標籤

用replace刪去

s=''.join('%s' %id for id in content)

t=''.join('%s' %id for id in title)

s=s.replace('

','')

t=t.replace('','')

t=t.replace('','')

t=t.replace('

','')

接下來就是用for迴圈遍歷所有的文章

第一章的url=11987333.html

最後一章的url=11989832.html

只有最後的四個數字變了,那麼就開始遍歷

是不是感覺沒有問題?那麼開啟我們寫入的檔案看看

what?這些問號什麼鬼

還是用replace,

是什麼?就是空格啦,本質就是

\xa0

啦,反正我是這麼理解的,所以

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

替換吧

解決了,沒有問題了似乎一切都搞定了,但是嗯嗯嗯.....還有乙個問題,低效率,是的低效率

for i in range(11987333,11989832):

按照這個規律第二章最後的數字應該是11987333但實際上最後的資料是

11987335

第二章比第一章大了2個數字,那麼第三章呢?比第二章大了

3個數字。

11987338.html

但是不搭嘎,反正我累了。

最後附源**:

import requests

import os

import re

from bs4 import beautifulsoup

start_url=""

for i in range(11987333,11989832):

url=start_url+str(i)+'.html'

html=requests.get(url,timeout=15)

soup=beautifulsoup(html.content,'lxml')

title=soup.find_all('div',class_='h1title')

content=soup.find_all('div',id='htmlcontent')

s=''.join('%s' %id for id in content)

t=''.join('%s' %id for id in title)

s=s.replace('

','')

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

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

t=t.replace('','')

t=t.replace('','')

t=t.replace('

','')

print(t)

with open("召喚千軍

.txt",'a') as f:

f.write(t)

f.write(s)

f.close()

大佬們看了多提意見唄,萌新乙個呢。這還搞了好久的  感覺智商收到了碾壓

Python爬取小說

感覺這個夠蛋疼的,因為你如果正常寫的話,前幾次執行沒問題,之後你連 都沒改,再執行就出錯了。其實這可能是網路請求失敗,或者有反爬蟲的東西吧。但這就會讓你寫的時候非常苦惱,所以這這東西,健壯性及其重要!import requests from bs4 import beautifulsoup impo...

python 爬取小說

前些天突然想看一些 可能是因為壓力大,所以就要有補償機制吧。為了節省流量,就想著把內容爬下來,然後就可以在路上看了。於是有了下面的指令碼。usr bin env python coding utf 8 import requests from lxml import etree 為了解決unicod...

python爬取小說

一 準備 安裝 requests pyquery庫 二 使用 定義了search類 初始化時傳入 第一章url 和 名即可 再呼叫all content方法即可 coding utf8 import re import requests from requests.exceptions import...