您好,登錄后才能下訂單哦!
這篇文章主要介紹如何使用Python3制作一個帶GUI界面的小說爬蟲工具,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
最近幫朋友寫個簡單爬蟲,順便整理了下,搞成了一個帶GUI界面的小說爬蟲工具,用來從筆趣閣爬取小說。
1.多線程采集,一個線程采集一本小說
2.支持使用代理,尤其是多線程采集時,不使用代理可能封ip
3.實時輸出采集結果
使用 threading.BoundedSemaphore() pool_sema.acquire() pool_sema.release()
來限制線程數量,防止并發線程過。具體限制數量,可在軟件界面輸入,默認5個線程
# 所有線程任務開始前 pool_sema.threading.BoundedSemaphore(5) # 具體每個線程開始前 鎖 pool_sema.acquire() .... # 線程任務執行結束釋放 pol_sema.release()
pip install requests pip install pysimplegui pip install lxml pip install pyinstaller
GUI 界面使用了一個tkinter 的封裝庫 PySimpleGUI
, 使用非常方便,雖然界面不夠漂亮,但勝在簡單,非常適合開發些小工具。https://pysimplegui.readthedocs.io/en/latest/比如這個界面的布局,只需簡單幾個 list
layout = [ [sg.Text('輸入要爬取的小說網址,點此打開筆趣閣站點復制', font=("微軟雅黑", 12), key="openwebsite", enable_events=True, tooltip="點擊在瀏覽器中打開")], [sg.Text("小說目錄頁url,一行一個:")], [ sg.Multiline('', key="url", size=(120, 6), autoscroll=True, expand_x=True, right_click_menu=['&Right', ['粘貼']] ) ], [sg.Text(visible=False, text_color="#ff0000", key="error")], [ sg.Button(button_text='開始采集', key="start", size=(20, 1)), sg.Button(button_text='打開下載目錄', key="opendir", size=(20, 1), button_color="#999999") ], [sg.Text('填寫ip代理,有密碼格式 用戶名:密碼@ip:端口,無密碼格式 ip:端口。如 demo:123456@123.1.2.8:8580')], [ sg.Input('', key="proxy"), sg.Text('線程數量:'), sg.Input('5', key="threadnum"), ], [ sg.Multiline('等待采集', key="res", disabled=True, border_width=0, background_color="#ffffff", size=( 120, 6), no_scrollbar=False, autoscroll=True, expand_x=True, expand_y=True, font=("宋體", 10), text_color="#999999") ], ]
pyinstaller -Fw start.py
import time import requests import os import sys import re import random from lxml import etree import webbrowser import PySimpleGUI as sg import threading # user-agent header = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36" } # 代理 proxies = {} # 刪除書名中特殊符號 # 筆趣閣基地址 baseurl = 'https://www.xbiquwx.la/' # 線程數量 threadNum = 6 pool_sema = None THREAD_EVENT = '-THREAD-' cjstatus = False # txt存儲目錄 filePath = os.path.abspath(os.path.join(os.getcwd(), 'txt')) if not os.path.exists(filePath): os.mkdir(filePath) # 刪除特殊字符 def deletetag(text): return re.sub(r'[\[\]#\/\\:*\,;\?\"\'<>\|\(\)《》&\^!~=%\{\}@!:。·!¥……() ]','',text) # 入口 def main(): global cjstatus, proxies, threadNum, pool_sema sg.theme("reddit") layout = [ [sg.Text('輸入要爬取的小說網址,點此打開筆趣閣站點復制', font=("微軟雅黑", 12), key="openwebsite", enable_events=True, tooltip="點擊在瀏覽器中打開")], [sg.Text("小說目錄頁url,一行一個:")], [ sg.Multiline('', key="url", size=(120, 6), autoscroll=True, expand_x=True, right_click_menu=['&Right', ['粘貼']] ) ], [sg.Text(visible=False, text_color="#ff0000", key="error")], [ sg.Button(button_text='開始采集', key="start", size=(20, 1)), sg.Button(button_text='打開下載目錄', key="opendir", size=(20, 1), button_color="#999999") ], [sg.Text('填寫ip代理,有密碼格式 用戶名:密碼@ip:端口,無密碼格式 ip:端口。如 demo:123456@123.1.2.8:8580')], [ sg.Input('', key="proxy"), sg.Text('線程數量:'), sg.Input('5', key="threadnum"), ], [ sg.Multiline('等待采集', key="res", disabled=True, border_width=0, background_color="#ffffff", size=( 120, 6), no_scrollbar=False, autoscroll=True, expand_x=True, expand_y=True, font=("宋體", 10), text_color="#999999") ], ] window = sg.Window('采集筆趣閣小說', layout, size=(800, 500), resizable=True,) while True: event, values = window.read() if event == sg.WIN_CLOSED or event == 'close': # if user closes window or clicks cancel break if event == "openwebsite": webbrowser.open('%s' % baseurl) elif event == 'opendir': os.system('start explorer ' + filePath) elif event == 'start': if cjstatus: cjstatus = False window['start'].update('已停止...點擊重新開始') continue window['error'].update("", visible=False) urls = values['url'].strip().split("\n") lenth = len(urls) for k, url in enumerate(urls): if (not re.match(r'%s\d+_\d+/' % baseurl, url.strip())): if len(url.strip()) > 0: window['error'].update("地址錯誤:%s" % url, visible=True) del urls[k] if len(urls) < 1: window['error'].update( "每行地址需符合 %s84_84370/ 形式" % baseurlr, visible=True) continue # 代理 if len(values['proxy']) > 8: proxies = { "http": "http://%s" % values['proxy'], "https": "http://%s" % values['proxy'] } # 線程數量 if values['threadnum'] and int(values['threadnum']) > 0: threadNum = int(values['threadnum']) pool_sema = threading.BoundedSemaphore(threadNum) cjstatus = True window['start'].update('采集中...點擊停止') window['res'].update('開始采集') for url in urls: threading.Thread(target=downloadbybook, args=( url.strip(), window,), daemon=True).start() elif event == "粘貼": window['url'].update(sg.clipboard_get()) print("event", event) if event == THREAD_EVENT: strtext = values[THREAD_EVENT][1] window['res'].update(window['res'].get()+"\n"+strtext) cjstatus = False window.close() #下載 def downloadbybook(page_url, window): try: bookpage = requests.get(url=page_url, headers=header, proxies=proxies) except Exception as e: window.write_event_value( '-THREAD-', (threading.current_thread().name, '\n請求 %s 錯誤,原因:%s' % (page_url, e))) return if not cjstatus: return # 鎖線程 pool_sema.acquire() if bookpage.status_code != 200: window.write_event_value( '-THREAD-', (threading.current_thread().name, '\n請求%s錯誤,原因:%s' % (page_url, page.reason))) return bookpage.encoding = 'utf-8' page_tree = etree.HTML(bookpage.text) bookname = page_tree.xpath('//div[@id="info"]/h2/text()')[0] bookfilename = filePath + '/' + deletetag(bookname)+'.txt' zj_list = page_tree.xpath( '//div[@class="box_con"]/div[@id="list"]/dl/dd') for _ in zj_list: if not cjstatus: break zjurl = page_url + _.xpath('./a/@href')[0] zjname = _.xpath('./a/@title')[0] try: zjpage = requests.get( zjurl, headers=header, proxies=proxies) except Exception as e: window.write_event_value('-THREAD-', (threading.current_thread( ).name, '\n請求%s:%s錯誤,原因:%s' % (zjname, zjurl, zjpage.reason))) continue if zjpage.status_code != 200: window.write_event_value('-THREAD-', (threading.current_thread( ).name, '\n請求%s:%s錯誤,原因:%s' % (zjname, zjurl, zjpage.reason))) return zjpage.encoding = 'utf-8' zjpage_content = etree.HTML(zjpage.text).xpath('//div[@id="content"]/text()') content = "\n【"+zjname+"】\n" for _ in zjpage_content: content += _.strip() + '\n' with open(bookfilename, 'a+', encoding='utf-8') as fs: fs.write(content) window.write_event_value( '-THREAD-', (threading.current_thread().name, '\n%s:%s 采集成功' % (bookname, zjname))) time.sleep(random.uniform(0.05, 0.2)) # 下載完畢 window.write_event_value('-THREAD-', (threading.current_thread( ).name, '\n請求 %s 結束' % page_url)) pool_sema.release() if __name__ == '__main__': main()
以上是“如何使用Python3制作一個帶GUI界面的小說爬蟲工具”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。