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

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

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

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

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

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

二、要獲取的天貓數據

三、數據抓取流程

四、源代碼

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


#------------------------接數據庫-----------------------------#
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()
#----------------------定義網頁操作函數--------------------------#
def py_click_element(browser,pos):
  #點擊網頁中的元素
  #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):
  #批量提取網頁內容
  length=len(xpaths)
  results=[0]*length
  for i in range(length):
    results[i]=py_extract_xpath(browser, xpaths[i])
  return results

#-----------------------------數據庫操作函數---------------------------#


#-----------------------------數據提取函數----------------------------#
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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • Python實現自動登錄百度空間的方法

    Python實現自動登錄百度空間的方法

    這篇文章主要介紹了Python實現自動登錄百度空間的方法,涉及Python的http請求發(fā)送、獲取響應、cookie操作等相關技巧,需要的朋友可以參考下
    2017-06-06
  • Python多進程方式抓取基金網站內容的方法分析

    Python多進程方式抓取基金網站內容的方法分析

    這篇文章主要介紹了Python多進程方式抓取基金網站內容的方法,結合實例形式分析了Python多進程抓取網站內容相關實現技巧與操作注意事項,需要的朋友可以參考下
    2019-06-06
  • Python正則表達式匹配中文用法示例

    Python正則表達式匹配中文用法示例

    這篇文章主要介紹了Python正則表達式匹配中文用法,結合實例形式分析了Python針對中文的正則與文件操作相關技巧,需要的朋友可以參考下
    2017-01-01
  • Python+?Flask實現Mock?Server詳情

    Python+?Flask實現Mock?Server詳情

    這篇文章主要介紹了Python+?Flask實現Mock?Server詳情,文章圍繞主題展開詳細的內容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-09-09
  • 淺談Python中的作用域規(guī)則和閉包

    淺談Python中的作用域規(guī)則和閉包

    本文簡單講解了PYTHON的閉包,作用域的基本知識配合實例簡單明了,適合初學者
    2018-03-03
  • Python?yield?關鍵詞,

    Python?yield?關鍵詞,

    這篇文章主要介紹了Python?yield?關鍵詞,要理解yield的作用,你必須理解生成器是什么。在理解生成器之前,必須先理解迭代器。下面文章我們就先從
    迭代器開始展開yield關鍵詞的相關自資料 ,需要的朋友可以參考一下
    2021-12-12
  • python繪制簡單折線圖代碼示例

    python繪制簡單折線圖代碼示例

    這篇文章主要介紹了python繪制簡單折線圖代碼示例,具有一定借鑒價值,需要的朋友可以參考下。
    2017-12-12
  • Python基于回溯法解決01背包問題實例

    Python基于回溯法解決01背包問題實例

    這篇文章主要介紹了Python基于回溯法解決01背包問題,結合實例形式分析了Python回溯法采用深度優(yōu)先策略搜索解決01背包問題的相關操作技巧,需要的朋友可以參考下
    2017-12-12
  • python中內置函數range詳解

    python中內置函數range詳解

    Python內置函數range()是一個用于生成一系列連續(xù)的整數的函數,它常用于循環(huán)結構中,用于指定循環(huán)的次數或迭代的范圍,這篇文章主要介紹了python之內置函數range,需要的朋友可以參考下
    2023-07-07
  • Python?threading和Thread模塊及線程的實現

    Python?threading和Thread模塊及線程的實現

    這篇文章主要介紹了Python?threading和Thread模塊及線程的實現,Python通過兩個標準庫thread和threading提供對線程的支持,threading對thread進行了封裝,具體實現介紹需要的朋友可以參考一下下面文章內容
    2022-06-06

最新評論

九寨沟县| 佳木斯市| 府谷县| 新蔡县| 彭州市| 永嘉县| 宜州市| 平湖市| 隆昌县| 绍兴市| 永泰县| 嘉义市| 无极县| 吉林市| 奉贤区| 子长县| 丹凤县| 民乐县| 夏河县| 抚顺市| 泊头市| 伊春市| 漳州市| 满洲里市| 左权县| 内丘县| 平阴县| 三门县| 衢州市| 庄河市| 营山县| 磐石市| 大新县| 南安市| 平罗县| 涟源市| 漠河县| 清远市| 达拉特旗| 确山县| 潞西市|