警告:本文代碼僅供學習,禁止違法使用或商用。
這裡拿人氣小說《黎明之劍》來舉個栗子,喜歡小說《黎明之劍》的朋友們請支援正版閱讀。
筆趣閣網站上的其他書籍基本上的都可以套用,其他盜版網站也基本上是差不多的思路就可以解決。
稍微改改就能很輕松的通過小說目錄頁下載下傳全本,我這裡就懶得弄了,有興趣的朋友可以試一試。
# -*- coding:UTF-8 -*-
# 作者部落格:https://www.cnblogs.com/Raine/
# 2019-06-20
import requests
from bs4 import BeautifulSoup
class TheLatest(object):
# 測試爬取筆趣閣《黎明之劍》最新章節
def __init__(self):
self.url_dir = 'https://www.biqiuge.com/book/36438/'
self.bookname = "" # 存放書籍名
self.chaptername = "" # 存放章節名
self.url_latest = "" # 存放最新章節連結
self.get_download_url()
def get_download_url(self):
# 直接從網頁head标簽内擷取想要的内容
r1 = requests.get(self.url_dir)
# 網頁是GBK編碼,需要轉換
r1.encoding = 'GBK'
html_1 = r1.text
bs_div = BeautifulSoup(html_1, 'lxml')
# 找到需要用到的标簽然後提取屬性
_bookname = bs_div.find('meta', property="og:novel:book_name")
self.bookname = _bookname.get('content')
_chaptername = bs_div.find('meta', property='og:novel:latest_chapter_name')
self.chaptername = _chaptername.get('content')
_url_latest = bs_div.find('meta', property='og:novel:latest_chapter_url')
self.url_latest = _url_latest.get('content')
def get_content(self):
r2 = requests.get(self.url_latest)
r2.encoding = 'GBK'
html_content = r2.text
bs_div = BeautifulSoup(html_content, 'lxml')
txt = bs_div.find('div', 'showtxt')
# 優化文字排版
txt = txt.text.replace(' ', '\n ')
txt = txt.replace('�6�1', '·')
out_content = txt.split(self.url_latest)[0]
return out_content
if __name__ == '__main__':
txt_content = TheLatest()
filename = txt_content.bookname + txt_content.chaptername + '.txt'
with open(filename, 'w', encoding='utf-8') as f:
f.write(txt_content.get_content())
參考資料:
Python3網絡爬蟲快速入門實戰解析 :https://cuijiahua.com/blog/2017/10/spider_tutorial_1.html
Python——爬蟲【Requests設定請求頭Headers】:https://blog.csdn.net/ysblogs/article/details/88530124
Python3.x爬蟲教程:爬網頁、爬圖檔、自動登入 :https://blog.csdn.net/Evankaka/article/details/46849095