最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python基于多線程實現(xiàn)抓取數(shù)據(jù)存入數(shù)據(jù)庫的方法

 更新時間:2018年06月22日 14:58:20   作者:zn505119020  
這篇文章主要介紹了Python基于多線程實現(xiàn)抓取數(shù)據(jù)存入數(shù)據(jù)庫的方法,結(jié)合實例形式分析了Python使用數(shù)據(jù)庫類與多線程類進行數(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è)計有所幫助。

相關(guān)文章

  • Python實現(xiàn)list反轉(zhuǎ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ù)使用方法解析

    這篇文章主要介紹了Python map及filter函數(shù)使用方法解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-08-08
  • 使用tensorboard可視化loss和acc的實例

    使用tensorboard可視化loss和acc的實例

    今天小編就為大家分享一篇使用tensorboard可視化loss和acc的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • Python中的配對函數(shù)zip()解讀

    Python中的配對函數(shù)zip()解讀

    這篇文章主要介紹了Python中的配對函數(shù)zip()解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • python命令行參數(shù)用法實例分析

    python命令行參數(shù)用法實例分析

    這篇文章主要介紹了python命令行參數(shù)用法,結(jié)合實例形式分析了Python基于optparse模塊處理命令行參數(shù)相關(guān)使用技巧,需要的朋友可以參考下
    2019-06-06
  • 教你用Pygame制作簡單的貪吃蛇游戲

    教你用Pygame制作簡單的貪吃蛇游戲

    貪吃蛇(也叫做貪食蛇)游戲是一款休閑益智類游戲,既簡單又耐玩,唯一的目標就是做這條gai上最長(pang)的蛇(zhu),這篇文章主要給大家介紹了關(guān)于如何使用Pygame制作簡單的貪吃蛇游戲的相關(guān)資料,需要的朋友可以參考下
    2022-06-06
  • Python腳本實現(xiàn)自動將數(shù)據(jù)庫備份到 Dropbox

    Python腳本實現(xiàn)自動將數(shù)據(jù)庫備份到 Dropbox

    本文給大家分享的是作者使用python腳本實現(xiàn)自動備份mysql數(shù)據(jù)庫到的dropbox網(wǎng)盤的代碼,非常的簡單實用,有需要的小伙伴可以參考下
    2017-02-02
  • python遞歸函數(shù)用法詳解

    python遞歸函數(shù)用法詳解

    在本篇文章里小編給大家整理的是一篇關(guān)于python遞歸函數(shù)用法詳解,有需要的朋友們可以參考學(xué)習(xí)下。
    2020-10-10
  • python通用日志使用小結(jié)

    python通用日志使用小結(jié)

    日志則是程序中非常重要的一部分,它可以記錄程序運行中的異常、警告等信息,方便開發(fā)人員調(diào)試程序,本文就來介紹一下python通用日志使用小結(jié),感興趣的可以了解一下
    2023-11-11
  • python通過floor函數(shù)舍棄小數(shù)位的方法

    python通過floor函數(shù)舍棄小數(shù)位的方法

    這篇文章主要介紹了python通過floor函數(shù)舍棄小數(shù)位的方法,實例分析了Python中floor函數(shù)的功能及使用技巧,需要的朋友可以參考下
    2015-03-03

最新評論

溧阳市| 简阳市| 洛隆县| 南乐县| 宝丰县| 阿克陶县| 东阳市| 新源县| 互助| 阿瓦提县| 西贡区| 锡林郭勒盟| 北票市| 望奎县| 昔阳县| 泽普县| 临湘市| 娄底市| 信宜市| 井陉县| 独山县| 施秉县| 靖江市| 莆田市| 竹北市| 普宁市| 苍南县| 张掖市| 呈贡县| 满城县| 县级市| 伊金霍洛旗| 烟台市| SHOW| 鹤峰县| 霍城县| 泰来县| 大埔县| 莫力| 安徽省| 叙永县|