爬蟲實戰-爬取小說資訊
阿新 • • 發佈:2022-11-30
import requests import parsel import csv for i in range(1,5): print(f"--------爬取第{i}頁-----------") url = f'https://www.slyqw.com/sort/{i}' header = { 'User-Agent': 'Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 107.0.0.0Safari / 537.36', 'Cookie': 'zh_choose = s;Hm_lvt_c4eec4b108dac241786b4218f0d27642 = 1669790844;Hm_lpvt_c4eec4b108dac241786b4218f0d27642 = 1669791342', 'Referer': 'https: // www.slyqw.com / whole.html' } # 通過requests 模擬傳送請求 r = requests.get(url=url,headers=header) response = r.text # 引入pansel模組 response = parsel.Selector(response) lis = response.css('.flex li') for li in lis: leibie = li.css('.img_span span::text').getall() # 小說類別 title = li.css('.w100 a h2::text').getall() # 小說標題 zuozhe = li.css('.w100 div i::text').getall() # 小說作者 zishu = li.css('.w100 div .orange::text').getall() # 小說字數 shijian = li.css('.w100 div .blue::text').getall() # 小說釋出時間 jieshao = li.css('.w100 p::text').getall() # 小說簡介 with open('小說連載.csv',mode='a',encoding='utf-8-sig',newline='') as f: # 這裡的newline='' 如果不加,會出現跳行空行 writefile = csv.writer(f) writefile.writerow([title,zuozhe,zishu,shijian,leibie,jieshao]) print("完成!")
以上資訊是爬取 5 頁小說的資訊。當然爬取資訊之後需要在excel裡面轉換替換一下不要的字元,這裡也可以在程式碼裡面直接寫 .replace()方法替換,我是直接用的excel的 ctrl+H 進行替換的。