35

手把手教你使用Python打造一个智能搜索淘宝商品,生成操作日志的系统

 3 years ago
source link: http://mp.weixin.qq.com/s?__biz=MzIzNTg3MDQyMQ%3D%3D&%3Bmid=2247495537&%3Bidx=2&%3Bsn=1c4f5cd660461a5eac38b0a32dd82a9d
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

VjqAju7.png!mobile

/1 前言/

随着网购的兴起,使得很多传统店铺转型做线上生意,电子商务的产生极大便利了我们的生活。

/2 项目目标/

通过Python程序一键搜索并直达目的地,爬取淘宝商品链接,商品名称,及商品的图片链接,并将每次的操作 记录在日志文件里。

/ 3  项目准备/

采用sublime text 3编辑器 编写程序,先看看程序运行后的主界面:

eaeYFzy.jpg!mobile

/4 项目实现/

1、分析页面结构并将商品信息放到各自列表中,就拿下面这个店铺为例。

Q3Mb6j2.jpg!mobile

2、老样子,F12 ,因为我们要找的是店铺的商品链接,所以我们尽可能找多的商品,从店铺的布局来看,好像就宝贝推荐这个板块的商品较多,所以,我们今天就爬这个板块内的所有内容。

yeuieuN.jpg!mobile

3、图中的 1,2,3步即是我们要爬的商品各种信息,可以看出商品全在class为photo的dt标签内,所以我们需要将他们提取出来。

try:


urllib3.disable_warnings() #从urllib3中消除警告


#网页请求


rep=requests.get(self.e2.get(),verify=False,timeout=4) #证书验证设为FALSE,设置访问延时


rep.encoding='gbk'


soup=BeautifulSoup(rep.content,'html.parser')


result=soup.find_all('dt',class_='photo') #获取到所有class为photo的dt元素


for x in result:


tt=x.find_all('a') #获取dt下的所有子元素a


for y in tt:


for x in y:


ab=x.find_next_siblings('img') #获取所有的下一个兄弟元素img


for z in ab:


\#将商品名称和商品图片链接添加到列表aa和bb中


aa.append(z['alt'])


bb.append('https:'+z['data-ks-lazyload'])


cc.append('https:'+y['href'])#将商品链接添加到列表cc中


except:


return

这样我们就轻松获取到了,商品的链接,商品名,商品图片链接,然后将他们分别保存在aa,bb,cc列表中。

/ 5  编写GUI界面,交互友好/

为了使运行结果更加美观,我们需要制作一个GUI界面,这就不得不提Python内置GUI神器 tkinter了。

好了,言归正传,我们编写交互式界面可以将他封装为一个类,这样更美观。

class page:


def __init__(self):


self.ti=dt.now().strftime("%Y/%m/%d %H:%S:%M")


self.root= tk.Tk() #初始化窗口


self.root.title('淘宝获取商家宝贝V1.0') #窗口名称


self.root.geometry("700x700") #设置窗口大小


self.root.iconbitmap('q.ico')


self.root.resizable(width=True,height=True) #设置窗口是否可变,宽不可变,高可变,默认为True


\#创建标签,文字,背景颜色,字体(颜色,大小),标签的高和宽


self.label1 =tk.Label(self.root,text='店铺首页:',font=('宋体',10),width=12,height=2)


\#创建输入框,标签高度,字体大小颜色,内容显示方式


self.e2 = tk.Entry(self.root,width=30,show=None, font=('Arial', 12)) # 显示成明文形式


self.label2 =tk.Label(self.root,text='淘宝直达:',font=('宋体',10),width=12,height=2)


self.e1 = tk.Entry(self.root,width=30,show=None, font=('Arial', 12))


\#创建按钮 内容 宽高 按钮绑定事件


self.b1 = tk.Button(self.root, text='解析页面', width=8,height=1,command=self.parse)


self.b2 =tk.Button(self.root, text='生成excel', width=8,height=1,command=self.sc)


self.b3 =tk.Button(self.root, text='淘宝搜索', width=8,height=1,command=self.search)


self.b4 =tk.Button(self.root, text='关闭程序', width=8,height=1,command=self.close)


self.b5 =tk.Button(self.root, text='保存日志', width=8,height=1,command=self.log)


\#创建文本框


self.te=tk.Text(self.root,height=40)


self.label1.place(x=140,y=30,anchor='nw')


self.label2.place(x=138,y=70,anchor='nw')


\#将所有部件添加到界面中


self.e1.place(x=210,y=74,anchor='nw')


self.e2.place(x=210,y=34,anchor='nw')


self.b1.place(x=160,y=110,anchor='nw')


self.b2.place(x=240,y=110,anchor='nw')


self.b3.place(x=320,y=110,anchor='nw')


self.b4.place(x=400,y=110,anchor='nw')


self.b5.place(x=480,y=110,anchor='nw')


self.te.place(x=40,y=170,anchor='nw')


\#设置输入框开始文本


self.e1.delete(0, "end")


self.e1.insert(0, "请输入要搜索的商品")


self.root.mainloop()

这样就算是创建好GUI界面了,效果图如下:

V3uA73.jpg!mobile

/ 6  输入目标店铺首页地址,生成数据并导出Excel和记录日志/

1、通过输入淘宝店铺首页地址来得到数据,所以我们需要对程序进行一个判断处理,因为我们都是将他封装在类中的,所以需在每个函数括号里加入一个self,代码如下:

# 解析网页内容




def parse(self):


self.res()


if self.e2.get()=='': #判断输入框的值是否为空值


\#插入值到文本框


self.te.insert('insert',' 。。。。请 输 入 网 址 。。。。\n')


elif str(self.e2.get()).find('taobao.com')==-1 or aa=='':


self.te.insert('insert',' 。。。。地址不正确 。。。。\n')


else:


self.te.insert("insert","解析目标网页:%s\n\n"%self.e2.get())


self.te.insert("insert"," 。。。。。解 析 开 始 :。。。。。\n") #INSERT索引表示插入光标当前的位置


self.te.insert("insert","\n\n")


for x,y,z in zip(aa,bb,cc): #将数据所在列表合并


result=x+'\n'+y+'\n'+z+'\n\n'


self.te.insert("insert",result,"\n\n") #插入到文本框


self.te.insert("insert","\n\n") #插入空格


self.te.insert("end","解析完毕。。。。。\n")

2、生成Excel文件,代码如下:

# 保存结果到excel


def sc(self):


self.te.insert("insert"," 。。。。。开 始 生 成 :。。。。。\n")


av={'时间':self.ti,'商品名称':aa,'商品链接':cc,'商品图片链接':bb}


\#生成dataframe 多维数组


df=p.DataFrame(av,columns=['时间','商品名称','商品链接','商品图片链接'],index=range(len(aa)))


df.to_excel('22.xlsx', sheet_name='taobao') #生成excel


self.te.insert("end"," 。。。。生 成 完 毕。。。。。\n")

代码运行之后,得到下图效果:

7fI3Ynz.jpg!mobile

3、生成日志文件,代码如下:

# 保存日志
def log(self):


ss=str(self.te.get(0.0,'end')).split('\n') #分隔文本框内容


with open('1.txt','w',encoding='utf8') as f: #保存日志


for y in range(len(ss)):


rea=str(self.ti)+ss[y]+'\n'


f.write(rea)

代码运行之后,得到下图效果:

AnAJN32.jpg!mobile

/8 快捷搜索淘宝商品网页直达程序关闭/

要想一键搜索淘宝商品首先我们的找到淘宝的搜索地址,然后在进行get请求,给他传不同的值即可。一般搜索会涉及到一个关键字search。

这里我们先找到淘宝的搜索入口,地址为:

https://s.taobao.com/search?q=

然后再在后面传值即可,因为我们是要在浏览器中浏览,所以需要使用webbrowser这个模块,专门负责访问页面,他的用法是webbrowser.open(url)。

所以代码如下:

# 搜索商品
def search(self):


self.te.insert("insert"," 。。。。。打开浏览器 :。。。。。\n")


wb.open('https://s.taobao.com/search?q='+self.e1.get()) #打开 浏览器

最后就是关闭程序了。代码如下:

# 关闭程序
def close(self):


self.te.insert("insert"," 。。。。。关闭程序 :。。。。。\n")


self.root.destroy() #销毁窗口

/9 小结/

1、不建议抓取太多数据,容易对服务器造成负载,浅尝辄止即可。

2、本文基于Python网络爬虫,利用爬虫库,打造了一款简易的智能淘宝搜索系统,并且可以操作生成日志。

3、这个系统看似很简单,实则对于新手小白是个不小的挑战,甚至有些大佬也很容易掉坑,主要这个网页分析有点复杂多变,而且还会有很多让你蒙圈的异常。总的来说还是挺不错的一个练手项目,也算是对自己的一个考验吧,希望大家喜欢。

4如果需要本文源码的话,请在公众号后台回复“ 智能淘宝 ”关键字进行获取,觉得不错,记得给个star噢。

恋习Python

3aYRBzB.png!mobile

关注恋习Python,Python都好练

好文章,我 在看 :heart:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK