本文共 2310 字,大约阅读时间需要 7 分钟。
挺久没更新简书了,之前一直在忙机器视觉的开题报告,现在又要期末复习,射频通信,信号处理看的脑阔疼,所以决定写个简单点的爬虫,放松下,换个环境,也顺便巩固下爬虫。
1:从上图中可以看出本次爬虫所用到的库,其中xlsxwriter
库是用来制作excel表格存储数据的,剩余两个库就不用多说了,爬虫必备库,你一定接触过。
import requestsimport reimport xlsxwriterdef getUrl(page): # page为[0,10]内的整数 part1 = 'https://shopsearch.taobao.com/search?app=shopsearch&spm=a230r.7195193.0.0.45xMl6&q=%E9%A3%9F%E5%93%81&tracelog=shopsearchnoqcat&s=' list = [] for a in range(0, page): part2 = '{}'.format(20*a) url = part1 + part2 list.append(url) return listdef getHtmlText(url): try: headers = { 隐藏,因为每个人都不一样,可通过F12获取,具体方法自行百度 Cookie 和 User-Agent必须要 } res = requests.get(url, headers=headers, timeout=30) res.raise_for_status() res.encoding = res.apparent_encoding # time.sleep(1) return res.text except: return '网络异常'def getTaobaoData(text): NAME = re.findall('"nick":"(.*?)"', text) PLACE = re.findall('"provcity":"(.*?)"', text) Totalsold = re.findall('"totalsold":(.*?),', text) Procnt = re.findall('"procnt":(.*?),', text) return NAME, PLACE, Totalsold, Procntdef main(page): num = 0 List = getUrl(page) TaobaoData = xlsxwriter.Workbook('E:\\taobaodata.xlsx') StoresData = TaobaoData.add_worksheet() title = [u'店铺', u'地址', u'销量', u'产品数'] StoresData.write_row('A1', title) StoresData.set_column('A:D', 25) for URL in List: Text = getHtmlText(URL) name, place, totalsold, procnt = getTaobaoData(Text) StoresData.write_column(1+20*num, 0, name) StoresData.write_column(1+20*num, 1, place) StoresData.write_column(1+20*num, 2, totalsold) StoresData.write_column(1+20*num, 3, procnt) num += 1 if not name: print('第{}页爬取失败'.format(num)) else: print('第{}页爬取成功'.format(num)) TaobaoData.close()if __name__ == '__main__': a = input('请输入需要爬取的页数(建议小于10):') main(int(a))
转载地址:http://fdjoo.baihongyu.com/