侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python如何抓取天猫商品详细信息及交易记录

Python  /  管理员 发布于 7年前   161

本文实例为大家分享了Python抓取天猫商品详细信息及交易记录的具体代码,供大家参考,具体内容如下

一、搭建Python环境

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

二、要获取的天猫数据

三、数据抓取流程

四、源代码

#coding:utf-8import spynnerfrom scrapy.selector import Selectorfrom bs4 import BeautifulSoupimport randomimport 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="" rel="external nofollow" rel="external nofollow" ]'  browser.click(pos)  browser.wait(random.randint(3,10))  return browserdef py_click_xpath(browser,xpath):  xpath=xpath+'/@href'  inner_href=Selector(text=browser.html).xpath(xpath).extract()  pos='a[href="https:/article/'+str(inner_href[0])+'" rel="external nofollow" ]'  browser=py_click_element(browser, pos)  return browserdef py_webpage_load(browser,url):  browser.load(url,load_timeout=60)  browser.wait(10)  return browserdef py_check_element(browser,xpath):  #按照xpath查找元素,如果存在则返回True,否则返回False  if Selector(text=browser.html).xpath(xpath).extract()!=[]:    return True  else:    return Falsedef 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="" 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="" 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列表生成式与列表生成器的使用
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客