欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python如何抓取天貓商品詳細(xì)信息及交易記錄

 更新時(shí)間:2018年02月23日 15:08:55   作者:lwhusted  
這篇文章主要為大家詳細(xì)介紹了Python如何抓取天貓商品詳細(xì)信息及交易記錄,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了Python抓取天貓商品詳細(xì)信息及交易記錄的具體代碼,供大家參考,具體內(nèi)容如下

一、搭建Python環(huán)境

本帖使用的是Python 2.7
涉及到的模塊:spynner, scrapy, bs4, pymmssql

二、要獲取的天貓數(shù)據(jù)

三、數(shù)據(jù)抓取流程

四、源代碼

#coding:utf-8
import spynner
from scrapy.selector import Selector
from bs4 import BeautifulSoup
import random
import pymssql


#------------------------接數(shù)據(jù)庫(kù)-----------------------------#
server="localhost"
user="sa"
password = "123456"
conn=pymssql.connect(server,user,password,"TmallData")
if conn:
  print "DataBase connecting successfully!"
else:
  print "DataBase connecting error!"
cursor=conn.cursor()
#----------------------定義網(wǎng)頁(yè)操作函數(shù)--------------------------#
def py_click_element(browser,pos):
  #點(diǎn)擊網(wǎng)頁(yè)中的元素
  #pos example:'a[href="#description" rel="external nofollow" rel="external nofollow" ]'
  browser.click(pos)
  browser.wait(random.randint(3,10))
  return browser

def py_click_xpath(browser,xpath):
  xpath=xpath+'/@href'
  inner_href=Selector(text=browser.html).xpath(xpath).extract()
  pos='a[href="'+str(inner_href[0])+'" rel="external nofollow" ]'
  browser=py_click_element(browser, pos)
  return browser

def py_webpage_load(browser,url):
  browser.load(url,load_timeout=60)
  browser.wait(10)
  return browser

def py_check_element(browser,xpath):
  #按照xpath查找元素,如果存在則返回True,否則返回False
  if Selector(text=browser.html).xpath(xpath).extract()!=[]:
    return True
  else:
    return False

def py_extract_xpath(browser,xpath):
  if py_check_element(browser, xpath):
    return Selector(text=browser.html).xpath(xpath).extract()[0]
  else:
    return "none"

def py_extract_xpaths(browser,xpaths):
  #批量提取網(wǎng)頁(yè)內(nèi)容
  length=len(xpaths)
  results=[0]*length
  for i in range(length):
    results[i]=py_extract_xpath(browser, xpaths[i])
  return results

#-----------------------------數(shù)據(jù)庫(kù)操作函數(shù)---------------------------#


#-----------------------------數(shù)據(jù)提取函數(shù)----------------------------#
def py_getDealReord(doc):
  soup=BeautifulSoup(doc,'lxml')
  tr=soup.find_all('tr')
  total_dealRecord=[([0]*5)for i in range(len(tr))] 
  i=-1
  for this_tr in tr:
    i=i+1
    td_user=this_tr.find_all('td',attrs={'class':"cell-align-l buyer"})
    for this_td in td_user:
      total_dealRecord[i][0]=this_td.getText().strip(' ')
      #print username
    td_style=this_tr.find_all('td',attrs={'class':"cell-align-l style"})
    for this_td in td_style:
      total_dealRecord[i][1]=this_td.getText(',').strip(' ')
      #print style
    td_quantity=this_tr.find_all('td',attrs={'class':"quantity"})
    for this_td in td_quantity:
      total_dealRecord[i][2]=this_td.getText().strip(' ')
      #print quantity
    td_dealtime=this_tr.find_all('td',attrs={'class':"dealtime"})
    for this_td in td_dealtime:
      total_dealRecord[i][3]=this_td.find('p',attrs={'class':"date"}).getText()
      total_dealRecord[i][4]=this_td.find('p',attrs={'class':"time"}).getText()
  return total_dealRecord
#--------------------獲取要抓取的所有商品鏈接-----------------------#
cursor.execute("""
select * from ProductURLs where BrandName='NB'
""")


file=open("H:\\Eclipse\\TmallCrawling\\HTMLParse\\errLog.txt")
InProductInfo=cursor.fetchall()
browser=spynner.Browser()
for temp_InProductInfo in InProductInfo:

  url='https:'+temp_InProductInfo[2]

  BrandName=temp_InProductInfo[0]
  ProductType=temp_InProductInfo[1]
  print BrandName,'\t',ProductType,'\t',url
  #url= 'https://detail.tmall.com/item.htm?id=524425656711&rn=77636d6db8dea5e30060976fdaf9768d&abbucket=19' 

  try:
    browser=py_webpage_load(browser, url)
  except:
    print "Loading webpage failed."
    file.write(url)
    file.write('\n')
    continue

  xpaths=['//*[@id="J_PromoPrice"]/dd/div/span/text()',\
    '//*[@id="J_StrPriceModBox"]/dd/span/text()',\
    '//*[@id="J_DetailMeta"]/div[1]/div[1]/div/div[1]/h1/text()',\
    '//*[@id="J_PostageToggleCont"]/p/span/text()',\
    '//*[@id="J_EmStock"]/text()',\
    '//*[@id="J_CollectCount"]/text()',\
    '//*[@id="J_ItemRates"]/div/span[2]/text()',\
    '//*[@id="J_DetailMeta"]/div[1]/div[1]/div/ul/li[1]/div/span[2]/text()']
  out_ProductInfo=py_extract_xpaths(browser,xpaths)
  browser=py_click_element(browser,'a[href="#description" rel="external nofollow" rel="external nofollow" ]')
  ProductProperty=py_extract_xpath(browser, '//*[@id="J_AttrUL"]')
  soup=BeautifulSoup(ProductProperty,'lxml')
  li=soup.find_all('li')
  prop=''
  for this_li in li:
    prop=prop+this_li.getText()+'\\'
  prop=prop[0:len(prop)-1]
  out_ProductProperty=prop
  print out_ProductProperty
  cursor.execute("""
  Insert into py_ProductInfo values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  """,(BrandName,ProductType,url,\
     out_ProductInfo[2],out_ProductInfo[1],\
     out_ProductInfo[0],out_ProductInfo[7],\
     out_ProductInfo[1],out_ProductInfo[3],\
     out_ProductInfo[4],out_ProductInfo[5],\
     out_ProductProperty))
  conn.commit()
  Deal_PageCount=0
  browser=py_click_element(browser, 'a[href="#J_DealRecord" rel="external nofollow" ]')
  #browser.browse(True)
  DealRecord=py_extract_xpath(browser, '//*[@id="J_showBuyerList"]/table/tbody')
  out_DealRecord=py_getDealReord(DealRecord)
  for temp_DealRecord in out_DealRecord:
    if str(temp_DealRecord[4])=='0':
      continue
    cursor.execute("""
    Insert into DealRecord values(%s,%s,%s,%s,%s,%s)
    """,(url,temp_DealRecord[0],temp_DealRecord[1],\
       temp_DealRecord[2],temp_DealRecord[3],\
       temp_DealRecord[4]))
    conn.commit()
  Deal_PageCount=Deal_PageCount+1
  print "Page ",Deal_PageCount
  for i in range(6):
    if (i==0) or (i==2):
      continue
    xpath='//*[@id="J_showBuyerList"]/div/div/a['+str(i)+']'
    if py_check_element(browser,xpath):
      browser=py_click_xpath(browser, xpath)
      DealRecord=py_extract_xpath(browser, '//*[@id="J_showBuyerList"]/table/tbody')
      out_DealRecord=py_getDealReord(DealRecord)
      for temp_DealRecord in out_DealRecord:
        if str(temp_DealRecord[4])=='0':
          continue
        cursor.execute("""
        Insert into DealRecord values(%s,%s,%s,%s,%s,%s)
        """,(url,temp_DealRecord[0],temp_DealRecord[1],\
           temp_DealRecord[2],temp_DealRecord[3],\
           temp_DealRecord[4]))
        conn.commit()
      Deal_PageCount=Deal_PageCount+1
      print "Page ",Deal_PageCount
  while py_check_element(browser, '//*[@id="J_showBuyerList"]/div/div/a[6]'):
    browser=py_click_xpath(browser, '//*[@id="J_showBuyerList"]/div/div/a[6]')
    DealRecord=py_extract_xpath(browser, '//*[@id="J_showBuyerList"]/table/tbody')
    out_DealRecord=py_getDealReord(DealRecord)
    for temp_DealRecord in out_DealRecord:
      if str(temp_DealRecord[4])=='0':
        continue
      cursor.execute("""
      Insert into DealRecord values(%s,%s,%s,%s,%s,%s)
      """,(url,temp_DealRecord[0],temp_DealRecord[1],\
         temp_DealRecord[2],temp_DealRecord[3],\
         temp_DealRecord[4]))
      conn.commit()
    Deal_PageCount=Deal_PageCount+1
    print "Page ",Deal_PageCount

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 如何使用Python進(jìn)行PDF圖片識(shí)別OCR

    如何使用Python進(jìn)行PDF圖片識(shí)別OCR

    這篇文章主要介紹了如何使用Python進(jìn)行PDF圖片識(shí)別OCR,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2021-01-01
  • 在Python中使用next()方法操作文件的教程

    在Python中使用next()方法操作文件的教程

    這篇文章主要介紹了在Python中使用next()方法操作文件的教程,是Python入門(mén)中的基礎(chǔ)知識(shí),需要的朋友可以參考下
    2015-05-05
  • Python實(shí)現(xiàn)多功能音樂(lè)播放器詳解

    Python實(shí)現(xiàn)多功能音樂(lè)播放器詳解

    這篇文章主要介紹了如何通過(guò)Python制作一個(gè)簡(jiǎn)易的音樂(lè)播放器,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)或工作有一定價(jià)值,需要的可以參考一下
    2022-02-02
  • python 字典有序并寫(xiě)入json文件過(guò)程解析

    python 字典有序并寫(xiě)入json文件過(guò)程解析

    這篇文章主要介紹了python 字典有序并寫(xiě)入json文件過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-09-09
  • python如何向一個(gè)dataframe中新加一行

    python如何向一個(gè)dataframe中新加一行

    這篇文章主要介紹了python如何向一個(gè)dataframe中新加一行問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • 為什么在函數(shù)中運(yùn)行的?Python?代碼速度更快?

    為什么在函數(shù)中運(yùn)行的?Python?代碼速度更快?

    對(duì)于Python解釋器來(lái)說(shuō),讀取和寫(xiě)入局部變量比全局變量更容易和更快,因?yàn)樗鼈兊淖饔糜蚍秶^小
    2023-09-09
  • numpy.unique()使用方法

    numpy.unique()使用方法

    本文主要介紹了numpy.unique()使用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-02-02
  • python 列表中[ ]中冒號(hào)‘:’的作用

    python 列表中[ ]中冒號(hào)‘:’的作用

    中括號(hào)[ ]:用于定義列表或引用列表、數(shù)組、字符串及元組中元素位置,冒號(hào): 用于定義分片、步長(zhǎng)。這篇文章給大家介紹python 列表中[ ]中冒號(hào)‘:’的作用,感興趣的的朋友跟隨小編一起看看吧
    2019-04-04
  • Python中的TCP socket寫(xiě)法示例

    Python中的TCP socket寫(xiě)法示例

    最近在學(xué)習(xí)腳本語(yǔ)言python,所以下面這篇文章主要給大家介紹了關(guān)于Python中TCP socket寫(xiě)法的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們一起來(lái)看看吧
    2018-05-05
  • Python 圖像處理 Pillow 庫(kù)詳情

    Python 圖像處理 Pillow 庫(kù)詳情

    這篇文章主要介紹了Python 圖像處理 Pillow 庫(kù),圖像處理是常用的技術(shù),python 擁有豐富的第三方擴(kuò)展庫(kù),Pillow 是 Python3 最常用的圖像處理庫(kù),目前最高版本5.2.0。Python2 使用Pil庫(kù),兩者是使用方法差不多,區(qū)別在于類(lèi)的引用不同。下面來(lái)看看文章的詳細(xì)內(nèi)容
    2021-11-11

最新評(píng)論