python 爬取小說

2021-08-19 19:40:32 字數 1975 閱讀 8583

前些天突然想看一些**,可能是因為壓力大,所以就要有補償機制吧。為了節省流量,就想著把內容爬下來,然後就可以在路上看了。於是有了下面的指令碼。

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import requests

from lxml import etree

# 為了解決unicodeencodeerror: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

# 下面注釋的三行在py2上可用,py3上無法找到reload(sys)方法

# import sys

# reload(sys)

# sys.setdefaultencoding('utf-8')

pagernum = 0

# 要儲存的檔案的名字

txtname = "斗羅大陸.txt"

hosturl = ""

lasturl = "/book/17251/4633486.html"

# 解析html並儲存

def parsehtml(r):

global pagernum # 這個是為了記錄一共多少網頁

s = etree.html(r.text)

title = s.xpath('//*[@class="bookname"]/h1/text()')[0] # 獲取title

print(title)

content = s.xpath('//*[@id="content"]/text()') # 獲取每一頁的**內容

print(content)

lasturl = nexturl[0]

print(lasturl)

# 以追加的形式開啟檔案

with open(txtname, 'a') as f:

f.write("\n")

# 新增.encode("utf-8") 是為了解決unicodeencodeerror: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

f.write(title.encode("utf-8"))

f.write("\n")

for str in content:

f.write(str.encode("utf-8"))

pagernum = pagernum + 1

print(pagernum) # 列印頁數

def gethtml(url):

r = requests.get(url)

r.encoding = 'gb2312' # 設定編碼格式

parsehtml(r)

if __name__ == "__main__":

while 'html' in lasturl:

url = hosturl + lasturl # 拼接url

print(url)

gethtml(url)

在寫的過程中遇到乙個問題

unicodeencodeerror: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

查了很多資料,解決方案都是**中最上面注釋掉的3行,但是,在py3上reload無法找到。內心很是崩潰,然後就換用了下面的方案。

所以:py2上

import sys

reload(sys)

sys.setdefaultencoding('utf-8')

一定要寫在最前面

py3上

title.encode("utf-8")

Python爬取小說

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

python爬取小說

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

Python爬取小說

這裡主要爬取筆趣閣的鏈結 因為筆趣閣對段時間的爬取次數做了限制,所以每次我們只能爬取十章 coding utf 8 import re import soup as soup from bs4 import beautifulsoup import requests import chardet i...