本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理,
前言
本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,如有問題請及時聯系我們以作處理,
一、相關環境配置
- python 3.6
- pycharm
- requests
- parsel
相關模塊 pip 安裝即可
二、使用步驟
1.引入庫
代碼如下(示例):
import requests import parsel
2.獲取網頁資料
代碼如下(示例):
url = 'https://www.tianyabook.com/top/allvote/' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36' } response = requests.get(url=url, headers=headers) response.encoding = response.apparent_encoding
運行回傳結果:
3.決議資料
代碼如下(示例):
selector = parsel.Selector(response.text) urls = selector.css('table tr td:nth-child(1) a::attr(href)').getall() titles = selector.css('table tr td:nth-child(1) a::attr(title)').getall() data = zip(urls, titles) for i in data: book_id = i[0].replace('.html', '').split('/')[-1] title = i[1] print(book_id, title)
運行回傳結果:
4.保存資料
def download(title, book_id): filename = 'D:\\python\\demo\\電子書下載\\小說\\' + title + '.txt' download_url = 'http://www.tianyabook.com/modules/article/txtarticle.php?id={}'.format(book_id) response_2 = requests.get(url=download_url, headers=headers) with open(filename, mode='a', encoding='utf-8') as f: f.write(response_2.text)
總結
提示:這里對文章進行總結:
以上就是全部的內容,本文僅僅簡單爬取小說網站,這里是直接訪問小說下載的地址,
以上文章來源于CSND,作者 嗨學編程
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/161527.html
標籤:其他
