Python爬取起点中文网小说信息及封面图片
生活随笔
收集整理的這篇文章主要介紹了
Python爬取起点中文网小说信息及封面图片
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 網站網址
- 分析
- 代碼
- 爬取結果
網站網址
https://www.qidian.com/all
共有5個頁面
分析
但是發現這個圖片很小,那怎么辦呢?
經過我的研究后發現,去掉地址后面的"/150",就好了
完美!!!
代碼
我是在桌面創建了一個名為“爬取起點中文網”,的文件夾,然后把py文件放在里面運行。所以在你運行我的代碼的時候,需要更改以下代碼,更改為你自己的文件路徑
os.chdir(r"C:\Users\dell\Desktop\爬取起點中文網")同樣你也可以修改存儲圖片的路徑。
當然py文件的名稱可以隨意定義,不會影響程序的運行
完整代碼如下:
# 導入相應的庫文件 import xlwt import requests from lxml import etree import os# 初始化列表,存入爬蟲數據 all_info_list = []# 定義獲取爬蟲信息的函數 def get_info(url):html = requests.get(url)selector = etree.HTML(html.text)# 定位大標簽,以此循環infos = selector.xpath('//ul[@class="all-img-list cf"]/li')for info in infos:title = info.xpath('div[2]/h4/a/text()')[0]author = info.xpath('div[2]/p[1]/a[1]/text()')[0]style_1 = info.xpath('div[2]/p[1]/a[2]/text()')[0]style_2 = info.xpath('div[2]/p[1]/a[3]/text()')[0]style = style_1+'·'+style_2complete = info.xpath('div[2]/p[1]/span/text()')[0]introduce = info.xpath('div[2]/p[2]/text()')[0].strip()info_list = [title, author, style, complete, introduce]# 把數據存入列表all_info_list.append(info_list)# 爬取小說封面圖片if not os.path.exists('./picture'):os.mkdir('./picture')img_src='https:'+info.xpath('div[1]/a/img/@src')[0]img_src=img_src[0:-4]img_name=title+'.jpg'img_data=requests.get(img_src).contentimg_path='picture/'+img_namewith open(img_path,'wb') as fp:fp.write(img_data)print(img_name,"下載成功")os.getcwd()os.chdir(r"C:\Users\dell\Desktop\爬取起點中文網")# 程序主入口 if __name__ == '__main__':urls = ['http://a.qidian.com/? page={}'.format(str(i)) for i in range(1, 6)]# 獲取所有數據print("開始爬取起點中文網小說封面圖片......")for url in urls:get_info(url)print("起點中文網小說封面圖片爬取完畢!")print("開始爬取起點中文網小說信息......")# 定義表頭header = ['title', 'author', 'style', 'complete', 'introduce']# 創建工作簿book = xlwt.Workbook(encoding='utf-8')# 創建工作表sheet = book.add_sheet('Sheet1')for h in range(len(header)):# 寫入表頭sheet.write(0, h, header[h])i = 1 # 行數for list in all_info_list:j = 0 # 列數# 寫入爬蟲數據for data in list:sheet.write(i, j, data)j += 1i += 1# 保存文件book.save('xiaoshuo.xls')print("起點中文網小說信息爬取完畢!")爬取結果
… …
總結
以上是生活随笔為你收集整理的Python爬取起点中文网小说信息及封面图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中心透视投影和鱼眼投影的区别(Centr
- 下一篇: websocket python爬虫_p