前提准備
安裝Python以及必要的模塊(requests,bs4),不了解requests和bs4的同學可以去官網看個大概之后再回來看教程
爬蟲思路
剛開始寫爬蟲的小白都有一個疑問,進行到什么時候爬蟲還會結束呢?答案是:爬蟲是在模擬真人在操作,所以當頁面中的next鏈接不存在的時候,就是爬蟲結束的時候。
1.用一個queue來存儲需要爬蟲的鏈接,每次都從queue中取出一個鏈接,如果queue為空,則程序結束
2.requests發出請求,bs4解析響應的頁面,提取有用的信息,將next的鏈接存入queue
3.用os來寫入txt文件
具體代碼
需要把域名和爬取網站對應的ip 寫入host文件中,這樣可以跳過DNS解析,不這樣的話,代碼運行一段時間會卡住不動
''' 抓取新筆趣閣https://www.xbiquge6.com/單個小說 爬蟲線路: requests - bs4 - txt Python版本: 3.7 OS: windows 10 ''' import requests import time import sys import os import queue from bs4 import BeautifulSoup # 用一個隊列保存url q = queue.Queue() # 首先我們寫好抓取網頁的函數 def get_content(url): try: headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36', } r = requests.get(url=url, headers=headers) r.encoding = 'utf-8' content = r.text return content except: s = sys.exc_info() print("Error '%s' happened on line %d" % (s[1], s[2].tb_lineno)) return " ERROR " # 解析內容 def praseContent(content): soup = BeautifulSoup(content,'html.parser') chapter = soup.find(name='div',class_="bookname").h1.text content = soup.find(name='div',id="content").text save(chapter, content) next1 = soup.find(name='div',class_="bottem1").find_all('a')[2].get('href') # 如果存在下一個章節的鏈接,則將鏈接加入隊列 if next1 != '/0_638/': q.put(base_url+next1) print(next1) # 保存數據到txt def save(chapter, content): filename = "修羅武神.txt" f =open(filename, "a+",encoding='utf-8') f.write("".join(chapter)+'\n') f.write("".join(content.split())+'\n') f.close # 主程序 def main(): start_time = time.time() q.put(first_url) # 如果隊列為空,則繼續 while not q.empty(): content = get_content(q.get()) praseContent(content) end_time = time.time() project_time = end_time - start_time print('程序用時', project_time) # 接口地址 base_url = 'https://www.xbiquge6.com' first_url = 'https://www.xbiquge6.com/0_638/1124120.html' if __name__ == '__main__': main()