python爬取天猫_Python如何抓取天猫商品详细信息及交易记录
本文实例为大家分享了Python抓取天猫商品详细信息及交易记录的具体代码,供大家参考,具体内容如下
一、搭建Python环境
本帖使用的是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://doofuu.com/article/4156231.html 目前在开发一款基于Python的基金爬取.分析.预测系统,目前已经开 ...
- python request url 转义_Python多线程抓取Google搜索链接网页
1)urllib2+BeautifulSoup抓取Goolge搜索链接 近期,参与的项目需要对Google搜索结果进行处理,之前学习了Python处理网页相关的工具.实际应用中,使用了urllib2和 ...
- python爬虫资源大全_Python爬虫抓取纯静态网站及其资源(基础篇)
本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理 以下文章来源于腾讯云 作者:程序员宝库 **( 想要学习Python?Python ...
- python 爬取作品集_Python批量抓取站酷ZCOOL作品图片并归档
前言 前几天,由于个人有需求,所以就要对站酷网一些类别下的作品的图片进行批量抓取,首先是采用的是NodeJs来写的,但是在运行的途中遇到很多的问题,所以后来就换成了Python,同时使用了多线程,使得 ...
- python爬虫app步骤_Python爬虫抓取手机APP的传输数据,python爬虫抓取app
Python爬虫抓取手机APP的传输数据,python爬虫抓取app 大多数APP里面返回的是json格式数据,或者一堆加密过的数据 .这里以超级课程表APP为例,抓取超级课程表里用户发的话题. 1. ...
- python唐诗分析综合_Python爬虫抓取唐诗宋词
一 说明 Python语言的爬虫开发相对于其他编程语言是极其高校的,在上一篇文章 爬虫抓取博客园前10页标题带有Python关键字(不区分大小写) 的文章中,我们介绍了使用requests做爬虫开发, ...
- python爬虫经典段子_Python爬虫-抓取糗事百科段子
爬虫其实很简单,只要用心,很快就就能掌握这门技术,下面通过实现抓取糗事百科段子,来分析一下为什么爬虫事实上是个非常简单的东西. 本文目标 抓取糗事百科热门段子 实现每按一次回车显示一个段子的发布时间, ...
- python selenium 处理弹窗_python+selenium 抓取弹出对话框信息
抓取弹出对话框信息,困挠了我很久,我百度了很久,一直没有找到我想要的内容.最近学习到了. 有两种方法: 1.driver.switch_to.alert.text 2.result = EC.aler ...
- python 弹出对话框_python+selenium 抓取弹出对话框信息
抓取弹出对话框信息,困挠了我很久,我百度了很久,一直没有找到我想要的内容.最近学习到了. 有两种方法: 1.driver.switch_to.alert.text 2.result = EC.aler ...
最新文章
- angular $observe() 和$watch的区别
- the value of esp was not properly saved
- python可视化神器_详解Python可视化神器Yellowbrick使用
- win7 右键增加打开 powershell选项
- 软件工程 - 版本管理 - git 的常用方法实例
- The Linux Process Principle, PID、PGID、PPID、SID、TID、TTY
- 连接设备不支持android,安卓手机不识别U盘、不能连接PC的处理方法
- Stackelberg博弈
- VS2019打包生成安装文件教程(详细实操版)
- C语言之一个有趣的关机程序
- 修改手机上网服务器,怎么给手机修改dns上网地址
- 姿态估计1-06:FSA-Net(头部姿态估算)-源码无死角讲解(1)-训练代码总览
- e4a 蓝牙温度app_单片机ESP8266无线传输DHT11温湿度(APP+E4A调试说明与程序设计)
- dom4j解析xml格式字符串获取标签属性和内容
- 链家租房市场分析(R爬虫、数据可视化)
- SpringBoot + FreeMarker + FlyingSaucer 实现PDF在线预览、打印、下载
- [七夕节]——一款基于canvas绘制五颜六色线条合成一个爱心发光动画特效
- 用计算机解题前 需要将解题方法,算法及其表示方法
- python 修改excel 路径_python更改已存在excel文件的方法
- vscode的seting配置
热门文章
- python实现数据恢复软件_恢复python
- 求电子在线商城后台管理系统
- 杭电计算机考研复试经验帖
- 【生信分析】clusterProfiler: universal enrichment tool for functional and comparative study(3)
- word表格导出为图像
- spring boot集成Elasticsearch客户端
- Eclipse中mvn install 报错error in opening zip file
- 不会编程也能爬数据!3个爬虫小工具教你实现~
- c语言GLUT头文件下载,GLUT教程.pdf
- SQL Server 数据库实验课第七周——授权:授予与收回