用py爬虫抓取天猫店信息(附源代码)

github地址:https://github.com/A-mermaid-Line-Engineer/python-begin.git
由于毕业论文要求,用Python做了一个爬虫抓取天猫店铺基本信息,在此共享。

1.安装Python2.7版本

访问https://www.python.org/


在Downloads列表选择window版本直接下载安装。和平时安装程序一样,可以参考百度经验http://jingyan.baidu.com/article/19192ad8399a62e53e5707e0.html

2.安装第三方库beautifulsoup

http://cuiqingcai.com/1319.html 这个博客中对beautifulsoup的安装讲的十分明白。
建议直接用Python自带的pip包安装
在命令行中输入

pip install beautifulsoup4

可能还需要安装lxml,同样的

pip install lxml

3.使用命令行运行程序

win+r调出搜索框,输入cmd调出亲切的黑底白字
输入 cd+空格+程序路径获取程序目录
输入 python+空格+anay.py(主程序名称)开始运行程序
在弹出的 Please input product:后输入你想抓取的商品品类,例如雪地靴
等待程序自动运行并声称表格。
注:抓取前50页大约3000条信息需要一个小时左右。也可以在主程序的page中修改抓取页数。

附:主程序源代码

抓取天猫店铺相关信息主程序代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# version python27
'''分析内容'''
from get_html import download_html as get
from bs4 import BeautifulSoup as bs
import re,sys,urllib
type = sys.getfilesystemencoding()
def get_url(key, page = 50):    #采集50页的内容,根据需求自己改
    print 'get urls...'
    keyword = urllib.quote(key.strip())
    urls = []
    i=1
    while(i<=page):
        url = "https://list.tmall.com/search_product.htm?type=pc&q=%s&totalPage=100&sort=s&style=g&from=mallfp..pc_1_suggest&suggest=0_1&jumpto=%d#J_Filter"%(keyword,i)
        urls.append(url)
        i = i + 1
    return urls
def get_content(url):
    html = get(url)
    soup = bs(html, 'lxml')
    res = soup.select(".ks-datalazyload")
    ms = re.compile(r"<em\sclass=\"count\"[\s\S]*?>([\s\S]*?)<\/em>",re.I|re.M)
    ar = re.compile(r"<li\sclass=\"locus\"[\s\S]*?>([\s\S]*?)<\/div>",re.I|re.M)
    age = re.compile(r"<span\sclass=\"tm-shop-age-content\"[\s\S]*?>([\s\S]*?)<\/span>",re.I|re.M)
    for i in res:
        try:
            s = ms.findall(str(i))
        except:
            s = ['None','None','None']
        try:
            area = ar.findall(str(i))
            areas = re.sub(r'<[^>]+>','',area[0].decode('utf-8').encode(type).strip())
            areas = areas.replace('\r','')
            areas = areas.replace('\n','')
            areas = areas.replace('\t','')
            areas = areas.replace(' ','')
        except:
            areas = 'None'
        try:
            ages = age.findall(str(i))
            agess = ages[0].decode('utf-8').encode(type).strip()
        except:
            agess = 'None'
        s.append(areas)
        s.append(agess)
    return s
def get_link(html):
    soup = bs(html ,'lxml')
    l = soup.select('.productTitle a')
    link = 'https:'+l[0].get('href')
    return link
def xls(key,url):
    keyword = urllib.quote(key.strip())
    html = get(url) 
    soup = bs(html, 'lxml')
    res = soup.select(".product-iWrap")
    p = re.compile(r"<p\sclass=\"productPrice\">([\s\S]*?)<\/p>",re.I|re.M)
    t = re.compile(r"<p\sclass=\"productTitle\">([\s\S]*?)<\/p>",re.I|re.M)
    c = re.compile(r"<p\sclass=\"productStatus\">([\s\S]*?)<\/span>",re.I|re.M)
    for i in res:
        try:
            price = re.sub(r'<[^>]+>','',p.search(str(i)).group(1)).decode('utf-8').encode(type).strip()
            title = re.sub(r'<[^>]+>','',t.search(str(i)).group(1)).decode('utf-8').encode(type).strip()
            count = re.sub(r'<[^>]+>','',c.search(str(i)).group(1)).decode('utf-8').encode(type).strip()
            link = get_link(str(i))
            con = get_content(link)
            with open(key+'.xls','a') as f:
                txt = '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n'%(title,price,count,con[0],con[1],con[2],con[3],con[4])
                f.write(txt)
        except:
            pass
        

key = raw_input("Please input product:")
if key.strip() == '':
    key = input("Please input product:")
urls = get_url(key)
f = open(key+'.xls','w')
title = '商品名称\t价格\t销量\t描述\t服务\t物流\t所在地\t开店时长\n'
f.write(title.decode('utf-8').encode(type))
f.close()
for u in urls:
    xls(key,u)
print 'End!'

通用抓取网页代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# version python27
'''下载网页'''
import urllib2,gzip,StringIO
def download_html(url, num_retries=2):
    print 'Download url:', url
    header = {'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'accept-encoding':'gzip, deflate, sdch, br',
    'accept-language':'en-US,en;q=0.8',
    'cache-control':'max-age=0',
    'user_agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'
    }
    try:
        req = urllib2.Request(url,headers = header)
        page = urllib2.urlopen(req,timeout=10)
        rpheader = page.info()
        body = page.read()
    except urllib2.URLError as e:
        print 'Download Error:', e.reason
        body = None
        if num_retries > 0:
            if hasattr(e, 'code') and 500 <= e.code < 600:
                return download_html(url, num_retries-1)
    encoding = rpheader.get("Content-Encoding")
    if encoding == 'gzip':
        content=gz_decoding(body).strip()
    else:
        content=body.strip()
    return content
def gz_decoding(data):
    compressedstream = StringIO.StringIO(data)  
    gziper = gzip.GzipFile(fileobj=compressedstream)    
    data2 = gziper.read() 
    return data2
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,458评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,454评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,171评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,062评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,440评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,661评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,906评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,609评论 0 200
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,379评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,600评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,085评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,409评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,072评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,088评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,860评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,704评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,608评论 2 270

推荐阅读更多精彩内容

  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    aimaile阅读 26,298评论 6 428
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,569评论 25 707
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • 2017年4月28日 下午两点多我们赶到静宁县天惠宾馆,稍作休息就赶到静宁四中,通过和校长班主任任课教师交...
    西风冽阅读 1,031评论 1 0
  • 人生,就是选择了,就要拼命往前,放弃了就不要后悔,毕竟,没有一条路是白走的。 在这个竞争激烈的社会,要么出众,要么...
    小犟阅读 221评论 0 0