Python基于多線程實現(xiàn)抓取數(shù)據(jù)存入數(shù)據(jù)庫的方法
本文實例講述了Python基于多線程實現(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, 并初始化,將實例用作屬性
def run(self):
while True:
success = True
item = self.queue.get() #調(diào)用隊列對象的get()方法從隊頭刪除并返回一個項目item
try:
self.spider.getDataById(item) #調(diào)用實例spider的方法getDataById(item)
except :
# print("失敗")
success = False
if not success :
self.queue.put(item)
logging.info("now queue size is: %d" % self.queue.qsize()) #隊列對象qsize()方法,返回隊列的大小
self.queue.task_done() #隊列對象在完成一項工作后,向任務(wù)已經(jīng)完成的隊列發(fā)送一個信號
class AmazonSpiderJob():
def __init__(self , size , qs):
self.size = size # 將形參size的值存儲到屬性變量size中
self.qs = qs
def work(self):
toSpiderQueue = Queue() #創(chuàng)建一個Queue隊列對象
for q in self.qs:
toSpiderQueue.put(q) #調(diào)用隊列對象的put()方法,在對尾插入一個項目item
for i in range(self.size):
t = ThreadCrawl(toSpiderQueue) #將實例用到一個類的方法中
t.setDaemon(True)
t.start()
toSpiderQueue.join() #隊列對象,等到隊列為空,再執(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進程與線程操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》、《Python+MySQL數(shù)據(jù)庫程序設(shè)計入門教程》及《Python常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
- Python讀寫及備份oracle數(shù)據(jù)庫操作示例
- Python實現(xiàn)定時備份mysql數(shù)據(jù)庫并把備份數(shù)據(jù)庫郵件發(fā)送
- Python實現(xiàn)備份MySQL數(shù)據(jù)庫的方法示例
- Python腳本實現(xiàn)自動將數(shù)據(jù)庫備份到 Dropbox
- python備份文件以及mysql數(shù)據(jù)庫的腳本代碼
- python使用多線程查詢數(shù)據(jù)庫的實現(xiàn)示例
- Python基于多線程操作數(shù)據(jù)庫相關(guān)問題分析
- python使用多線程備份數(shù)據(jù)庫的步驟
相關(guān)文章
Python實現(xiàn)list反轉(zhuǎn)實例匯總
這篇文章主要介紹了Python實現(xiàn)list反轉(zhuǎn)的方法,實例總結(jié)了關(guān)于list的各種較為常見的操作技巧,需要的朋友可以參考下2014-11-11
Python map及filter函數(shù)使用方法解析
這篇文章主要介紹了Python map及filter函數(shù)使用方法解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友可以參考下2020-08-08
Python腳本實現(xiàn)自動將數(shù)據(jù)庫備份到 Dropbox
本文給大家分享的是作者使用python腳本實現(xiàn)自動備份mysql數(shù)據(jù)庫到的dropbox網(wǎng)盤的代碼,非常的簡單實用,有需要的小伙伴可以參考下2017-02-02
python通過floor函數(shù)舍棄小數(shù)位的方法
這篇文章主要介紹了python通過floor函數(shù)舍棄小數(shù)位的方法,實例分析了Python中floor函數(shù)的功能及使用技巧,需要的朋友可以參考下2015-03-03

