python——爬虫学习——爬取淘宝搜索结果-(5)
来源:互联网 发布:人工智能黑客类小说 编辑:程序博客网 时间:2024/06/06 03:17
将requests,re库结合起来的一个爬取淘宝商品的程序:
# -*- coding: utf-8 -*import requestsimport reimport sys,locale#淘宝爬虫类class TAOBAO: #初始化,传入基地址,页数 def __init__(self,baseUrl,page,goods): self.goods=goods self.baseUrl=baseUrl+self.goods self.page=page self.defaultgoods=u"淘宝" self.ilt=[] self.file=None #传入url,获取页面代码 def getHTMLText(self,url): headers={'user-agent':"Mozilla/5.0 (Windows NT 6.3; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0",'Accept-Language':"zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"} try: r=requests.get(url,headers=headers,timeout=30) r.encoding=r.apparent_encoding return r.text except requests.exceptions.RequestException,e: print e #摘取所要数据 def parsePage(self,html): try: plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html) tlt = re.findall(r'\"raw_title\"\:\".*?\"',html) npl = re.findall(r'\"view_sales\"\:\"[\d]*',html) for i in range(len(plt)): price = eval(plt[i].split(':',1)[1]) title = eval(tlt[i].split(':',1)[1]) num = eval(npl[i].split(':"',1)[1]) self.ilt.append([price , num, title]) except: print("摘取数据出错").encode('utf-8') return None #打印数据 def printGoodsList(self): tplt = "{:^4}\t{:<14}\t{:<10}\t{:^80}" print (tplt.format("序号", "价格","成交量", "商品名称", ).decode('utf-8')) count = 0 for g in self.ilt: count = count + 1 print(tplt.format(count, g[0], g[1], g[2],chr(32))) #创建存入数据文件 def setFileTitle(self): self.file = open(goods + ".txt","w+") #写入数据 def writeData(self): tplt = "{:^4}\t{:<14}\t{:<10}\t{:^80}" self.file.write(tplt.format("序号", "价格","成交量", "商品名称", )+"\n") count = 0 for g in self.ilt: count = count + 1 self.file.write(tplt.format(count, g[0], g[1], g[2],chr(32))+"\n") def start(self): self.setFileTitle() for i in range(self.page): try: url = self.baseUrl + '&s=' + str(44*i) html = self.getHTMLText(url) self.parsePage(html) except: continue self.printGoodsList() self.writeData()goods=raw_input("输入想要查询的物品:").decode(sys.stdin.encoding or locale.getpreferredencoding(True))baseurl = "https://s.taobao.com/search?q="page=int(raw_input("输入想要查询的页数:"))tb = TAOBAO(baseurl,page,goods)tb.start()
0 0
- python——爬虫学习——爬取淘宝搜索结果-(5)
- Python爬虫爬取百度搜索结果——邮箱地址
- python爬虫爬取百度搜索结果
- python爬虫学习 之 定向爬取 淘宝商品价格
- Python爬虫——小说爬取
- Python简单爬虫——淘宝数据
- python爬虫(11)身边的搜索专家——获取百度搜索结果
- 【爬虫】爬取百度搜索结果页面
- 爬取百度搜索结果的爬虫
- 【Python学习笔记】利用Python爬取百度搜索结果
- python爬虫爬取淘宝网页
- Python爬虫-Selenium爬取淘宝美食
- python爬虫 爬取淘宝网页数据
- Python爬虫教程—python爬取糗事百科详解
- Python 爬虫-爬取pixiv特定搜索结果的所有作品-登陆
- Python 爬虫-爬取pixiv特定搜索结果的所有作品-抓取 分析 下载
- python爬虫学习笔记1——糗百段子爬取
- python爬虫学习笔记2——百度贴吧帖子爬取
- 裁完员还不够 外媒称乐视把美国总部大楼也卖了
- 字符串7:句子的逆序练习题
- 归并排序
- JavaScript学习笔记27-给对象添加一个方法
- 在Eclipse中创建简单Hibernate项目
- python——爬虫学习——爬取淘宝搜索结果-(5)
- 字符串8:字符串移位练习题
- STM32的Remap
- FCN训练自己的数据集及测试
- 【Android】Activity详解
- 微信小程序-页面跳转失败WAService.js:3 navigateTo:fail url not in app.json
- Minimum Inversion Number
- 4
- 字符串9:拼接最小字典序练习题