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è)置本地?cái)?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
#一個(gè)模塊中存儲(chǔ)多個(gè)類 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ì)列對(duì)象的get()方法從隊(duì)頭刪除并返回一個(gè)項(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ì)列對(duì)象qsize()方法,返回隊(duì)列的大小
self.queue.task_done() #隊(duì)列對(duì)象在完成一項(xiàng)工作后,向任務(wù)已經(jīng)完成的隊(duì)列發(fā)送一個(gè)信號(hào)
class AmazonSpiderJob():
def __init__(self , size , qs):
self.size = size # 將形參size的值存儲(chǔ)到屬性變量size中
self.qs = qs
def work(self):
toSpiderQueue = Queue() #創(chuàng)建一個(gè)Queue隊(duì)列對(duì)象
for q in self.qs:
toSpiderQueue.put(q) #調(diào)用隊(duì)列對(duì)象的put()方法,在對(duì)尾插入一個(gè)項(xiàng)目item
for i in range(self.size):
t = ThreadCrawl(toSpiderQueue) #將實(shí)例用到一個(gè)類的方法中
t.setDaemon(True)
t.start()
toSpiderQueue.join() #隊(duì)列對(duì)象,等到隊(duì)列為空,再執(zhí)行別的操作
3. 主線程類
from amazon_s import AmazonSpiderJob #從一個(gè)模塊中導(dǎo)入類
import pymysql
import pandas as pd
from local_data import Database
if __name__ == '__main__':
#初次跑程序的時(shí)候,需要?jiǎng)h除舊表,然后新建表,之后重啟再跑的時(shí)候需要注釋
#----------------------
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è)計(jì)入門教程》及《Python常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
- Python讀寫及備份oracle數(shù)據(jù)庫操作示例
- Python實(shí)現(xiàn)定時(shí)備份mysql數(shù)據(jù)庫并把備份數(shù)據(jù)庫郵件發(fā)送
- Python實(shí)現(xiàn)備份MySQL數(shù)據(jù)庫的方法示例
- Python腳本實(shí)現(xiàn)自動(dòng)將數(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ì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
如何把python項(xiàng)目部署到linux服務(wù)器
這篇文章主要介紹了如何把python項(xiàng)目部署到linux服務(wù)器,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
python定時(shí)任務(wù) sched模塊用法實(shí)例
這篇文章主要介紹了python定時(shí)任務(wù) sched模塊用法實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11
python是先運(yùn)行metaclass還是先有類屬性解析
這篇文章主要為大家介紹了python是先運(yùn)行metaclass還是先有類屬性的問題原理解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05
基于Python輕松制作一個(gè)股票K線圖網(wǎng)站
在當(dāng)今這個(gè)人手一個(gè)?Web?服務(wù)的年代,GUI?程序還是沒有?Web?服務(wù)來的香啊。所以本文將用Python制作一個(gè)簡單的股票K線圖網(wǎng)站,感興趣的可以了解一下2022-09-09
python中實(shí)現(xiàn)php的var_dump函數(shù)功能
這篇文章主要介紹了python中實(shí)現(xiàn)php的var_dump函數(shù)功能,var_dump函數(shù)在PHP中調(diào)試時(shí)非常實(shí)用,本文介紹在Python中實(shí)現(xiàn)這個(gè)函數(shù),需要的朋友可以參考下2015-01-01
Django中更改默認(rèn)數(shù)據(jù)庫為mysql的方法示例
這篇文章主要介紹了Django中更改默認(rèn)數(shù)據(jù)庫為mysql的方法示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-12-12
python解析中國天氣網(wǎng)的天氣數(shù)據(jù)
最近學(xué)習(xí)python 感覺這門腳本語言十分靈活 而且功能十分強(qiáng)大 尤其是他re庫用于正則匹配十分強(qiáng)大,寫了個(gè)例子解析中國天氣網(wǎng)2014-03-03

