Python基于多線程實(shí)現(xiàn)抓取數(shù)據(jù)存入數(shù)據(jù)庫的方法
本文實(shí)例講述了Python基于多線程實(shí)現(xiàn)抓取數(shù)據(jù)存入數(shù)據(jù)庫的方法。分享給大家供大家參考,具體如下:
1. 數(shù)據(jù)庫類
""" 使用須知: 代碼中數(shù)據(jù)表名 aces ,需要更改該數(shù)據(jù)表名稱的注意更改 """ import pymysql class Database(): # 設(shè)置本地數(shù)據(jù)庫用戶名和密碼 host = "localhost" user = "root" password = "" database = "test" port = 3306 charset = "utf8" cursor='' connet ='' def __init__(self): #連接到數(shù)據(jù)庫 self.connet = pymysql.connect(host = self.host , user = self.user,password = self.password , database = self.database, charset = self.charset) self.cursor = self.connet.cursor() # #刪表 def dropTables(self): self.cursor.execute('''''drop table if exists aces''') print("刪表") #建表 def createTables(self): self.cursor.execute('''''create table if not exists aces ( asin varchar(11) primary key not null, checked varchar(200));''') print("建表") #保存數(shù)據(jù) def save(self,aceslist): self.cursor.execute("insert into aces ( asin, checked) values(%s,%s)", (aceslist[0],aceslist[1])) self.connet.commit() #判斷元素是否已經(jīng)在數(shù)據(jù)庫里,在就返回true ,不在就返回false def is_exists_asin(self,asin): self.cursor.execute('select * from aces where asin = %s',asin) if self.cursor.fetchone() is None: return False return True # db =Database()
2. 多線程任務(wù)類
import urllib.parse import urllib.parse import urllib.request from queue import Queue import time import random import threading import logging import pymysql from bs4 import BeautifulSoup from local_data import Database #一個模塊中存儲多個類 AmazonSpeder , ThreadCrawl(threading.Thread), AmazonSpiderJob class AmazonSpider(): def __init__(self): self.db = Database() def randHeader(self): head_connection = ['Keep-Alive', 'close'] head_accept = ['text/html, application/xhtml+xml, */*'] head_accept_language = ['zh-CN,fr-FR;q=0.5', 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3'] head_user_agent = ['Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko', 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36', 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; rv:11.0) like Gecko)', 'Mozilla/5.0 (Windows; U; Windows NT 5.2) Gecko/2008070208 Firefox/3.0.1', 'Mozilla/5.0 (Windows; U; Windows NT 5.1) Gecko/20070309 Firefox/2.0.0.3', 'Mozilla/5.0 (Windows; U; Windows NT 5.1) Gecko/20070803 Firefox/1.5.0.12', 'Opera/9.27 (Windows NT 5.2; U; zh-cn)', 'Mozilla/5.0 (Macintosh; PPC Mac OS X; U; en) Opera 8.0', 'Opera/8.0 (Macintosh; PPC Mac OS X; U; en)', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.12) Gecko/20080219 Firefox/2.0.0.12 Navigator/9.0.0.6', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Win64; x64; Trident/4.0)', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)', 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E)', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Maxthon/4.0.6.2000 Chrome/26.0.1410.43 Safari/537.1 ', 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E; QQBrowser/7.3.9825.400)', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0 ', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.92 Safari/537.1 LBBROWSER', 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0; BIDUBrowser 2.x)', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/3.0 Safari/536.11'] header = { 'Connection': head_connection[0], 'Accept': head_accept[0], 'Accept-Language': head_accept_language[1], 'User-Agent': head_user_agent[random.randrange(0, len(head_user_agent))] } return header def getDataById(self , queryId): #如果數(shù)據(jù)庫中有的數(shù)據(jù),直接返回不處理 if self.db.is_exists_asin(queryId): return req = urllib.request.Request(url="https://www.amazon.com/dp/"+str(queryId) , headers=self.randHeader()) webpage = urllib.request.urlopen(req) html = webpage.read() soup = BeautifulSoup(html, 'html.parser') content = soup.find_all("span" , id = "asTitle") # 加入一種判斷,有的asin沒有該定位, if len(content): # 非空 state = content[0].string else: # 列表為空,沒有定位到 state = "other" print(queryId) print(state) self.db.save([queryId,state]) class ThreadCrawl(threading.Thread): #ThreadCrawl類繼承了Threading.Thread類 def __init__(self, queue): #子類特有屬性, queue FORMAT = time.strftime("[%Y-%m-%d %H:%M:%S]", time.localtime()) + "[AmazonSpider]-----%(message)s------" logging.basicConfig(level=logging.INFO, format=FORMAT) threading.Thread.__init__(self) self.queue = queue self.spider = AmazonSpider() #子類特有屬性spider, 并初始化,將實(shí)例用作屬性 def run(self): while True: success = True item = self.queue.get() #調(diào)用隊(duì)列對象的get()方法從隊(duì)頭刪除并返回一個項(xiàng)目item try: self.spider.getDataById(item) #調(diào)用實(shí)例spider的方法getDataById(item) except : # print("失敗") success = False if not success : self.queue.put(item) logging.info("now queue size is: %d" % self.queue.qsize()) #隊(duì)列對象qsize()方法,返回隊(duì)列的大小 self.queue.task_done() #隊(duì)列對象在完成一項(xiàng)工作后,向任務(wù)已經(jīng)完成的隊(duì)列發(fā)送一個信號 class AmazonSpiderJob(): def __init__(self , size , qs): self.size = size # 將形參size的值存儲到屬性變量size中 self.qs = qs def work(self): toSpiderQueue = Queue() #創(chuàng)建一個Queue隊(duì)列對象 for q in self.qs: toSpiderQueue.put(q) #調(diào)用隊(duì)列對象的put()方法,在對尾插入一個項(xiàng)目item for i in range(self.size): t = ThreadCrawl(toSpiderQueue) #將實(shí)例用到一個類的方法中 t.setDaemon(True) t.start() toSpiderQueue.join() #隊(duì)列對象,等到隊(duì)列為空,再執(zhí)行別的操作
3. 主線程類
from amazon_s import AmazonSpiderJob #從一個模塊中導(dǎo)入類 import pymysql import pandas as pd from local_data import Database if __name__ == '__main__': #初次跑程序的時候,需要刪除舊表,然后新建表,之后重啟再跑的時候需要注釋 #---------------------- db = Database() db.dropTables() db.createTables() #--------------------------- df = pd.read_excel("ASIN檢查_viogico_1108.xlsx") # print(df.info()) qs = df["asin1"].values print(qs) print(len(qs)) amazonJob = AmazonSpiderJob(8, qs) amazonJob.work()
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python進(jìn)程與線程操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》、《Python+MySQL數(shù)據(jù)庫程序設(shè)計入門教程》及《Python常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
- Python讀寫及備份oracle數(shù)據(jù)庫操作示例
- Python實(shí)現(xiàn)定時備份mysql數(shù)據(jù)庫并把備份數(shù)據(jù)庫郵件發(fā)送
- Python實(shí)現(xiàn)備份MySQL數(shù)據(jù)庫的方法示例
- Python腳本實(shí)現(xiàn)自動將數(shù)據(jù)庫備份到 Dropbox
- python備份文件以及mysql數(shù)據(jù)庫的腳本代碼
- python使用多線程查詢數(shù)據(jù)庫的實(shí)現(xiàn)示例
- Python基于多線程操作數(shù)據(jù)庫相關(guān)問題分析
- python使用多線程備份數(shù)據(jù)庫的步驟
相關(guān)文章
Pycharm學(xué)生免費(fèi)專業(yè)版安裝教程的方法步驟
這篇文章主要介紹了Pycharm學(xué)生免費(fèi)專業(yè)版安裝教程的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09如何把python項(xiàng)目部署到linux服務(wù)器
這篇文章主要介紹了如何把python項(xiàng)目部署到linux服務(wù)器,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08python定時任務(wù) sched模塊用法實(shí)例
這篇文章主要介紹了python定時任務(wù) sched模塊用法實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-11-11python是先運(yùn)行metaclass還是先有類屬性解析
這篇文章主要為大家介紹了python是先運(yùn)行metaclass還是先有類屬性的問題原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05python中實(shí)現(xiàn)php的var_dump函數(shù)功能
這篇文章主要介紹了python中實(shí)現(xiàn)php的var_dump函數(shù)功能,var_dump函數(shù)在PHP中調(diào)試時非常實(shí)用,本文介紹在Python中實(shí)現(xiàn)這個函數(shù),需要的朋友可以參考下2015-01-01Django中更改默認(rèn)數(shù)據(jù)庫為mysql的方法示例
這篇文章主要介紹了Django中更改默認(rèn)數(shù)據(jù)庫為mysql的方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12python解析中國天氣網(wǎng)的天氣數(shù)據(jù)
最近學(xué)習(xí)python 感覺這門腳本語言十分靈活 而且功能十分強(qiáng)大 尤其是他re庫用于正則匹配十分強(qiáng)大,寫了個例子解析中國天氣網(wǎng)2014-03-03