一个完整的大作业:淘宝口红销量top10的销量和评价

网站:淘宝口红搜索页

https://s.taobao.com/search?q=%E5%8F%A3%E7%BA%A2&sort=sale-desc先爬取该页面前十的口红的商品名、销售量、价格、评分以及评论数,发现该网页使用了json的方式,使用正则表达式匹配字段,抓取我们所需要的信息。启用用户代理爬取数据,预防该网站的反爬手段,并把结果存入到csv文件中,效果如下。

成功爬取到淘宝口红top10的基本信息后,发现评论并不在同一页面上,并且该页面存在着进入评论页的关键字,爬取下来后放入一个列表中,然后用循环整个列表和页数,使用

正则表达式,匹配评论的关键字,成功爬取淘宝top10口红的评论进十万条,如下图所示。


完整的源代码如下:

from urllib import request
import re
import csv
import time
itemId=[]
sellerId=[]
links=[]
titles=[]
# ,‘商品评分‘,‘评论总数‘
def get_product_info():
    fileName = ‘商品.csv‘
    comment_file = open(fileName, ‘w‘, newline=‘‘)
    write = csv.writer(comment_file)
    write.writerow([‘商品名‘, ‘连接‘, ‘销售量‘, ‘价格‘, ‘地址‘,‘商品评分‘,‘评论总数‘])
    comment_file.close()

    fileName2 = ‘评价.csv‘
    productfile = open(fileName2, ‘w‘, newline=‘‘)
    product_write = csv.writer(productfile)
    product_write.writerow([‘商品id‘,‘商品名‘,‘时间‘, ‘颜色分类‘, ‘评价‘])
    productfile.close()

def get_product():
    global itemId
    global sellerId
    global titles
    url = ‘https://s.taobao.com/search?q=%E5%8F%A3%E7%BA%A2&sort=sale-desc‘
    head = {}
    # 写入User Agent信息
    head[
        ‘User-Agent‘] = ‘Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19‘
    # 创建Request对象
    req = request.Request(url, headers=head)
    # 传入创建好的Request对象
    response = request.urlopen(req, timeout=30)
    # 读取响应信息并解码
    html = response.read().decode(‘utf-8‘)
    # 打印信息
    pattam_id = ‘"nid":"(.*?)"‘
    raw_title = ‘"raw_title":"(.*?)"‘
    view_price = ‘"view_price":"(.*?)"‘
    view_sales = ‘"view_sales":"(.*?)"‘
    item_loc = ‘"item_loc":"(.*?)"‘
    user_id = ‘"user_id":"(.*?)"‘
    all_id = re.compile(pattam_id).findall(html)
    all_title = re.compile(raw_title).findall(html)
    all_price = re.compile(view_price).findall(html)
    all_sales = re.compile(view_sales).findall(html)
    all_loc = re.compile(item_loc).findall(html)
    all_userid = re.compile(user_id).findall(html)
    print("开始收集信息")
    try:
        for i in range(10):
            this_id = all_id[i]
            this_title = all_title[i]
            this_price = all_price[i]
            this_sales = all_sales[i]
            this_loc = all_loc[i]
            this_userid = all_userid[i]
            id = str(this_id)
            title = str(this_title)
            price = str(this_price)
            sales = str(this_sales)
            loc = str(this_loc)
            uid = str(this_userid)
            link = ‘https://item.taobao.com/item.htm?id=‘ + str(id)
            shoplink = ‘https://dsr-rate.tmall.com/list_dsr_info.htm?itemId=‘ +str(id)
            head = {}
            # 写入User Agent信息
            head[
                ‘User-Agent‘] = ‘Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19‘
            # 创建Request对象
            req2 = request.Request(shoplink, headers=head)
            # 传入创建好的Request对象
            response2 = request.urlopen(req2, timeout=30)
            # 读取响应信息并解码
            html2 = response2.read().decode(‘utf-8‘)
            gradeAvg = ‘"gradeAvg":(.*?,)"‘
            rateTotal = ‘"rateTotal":(.*?,)"‘
            all_gradeAvg = re.compile(gradeAvg).findall(html2)
            all_rateTotal = re.compile(rateTotal).findall(html2)
            this_gradeAvg = all_gradeAvg
            this_rateTotal = all_rateTotal
            gradeAvg = str(this_gradeAvg)[2:-3]
            rateTotal = str(this_rateTotal)[2:-3]
            # print("平均分:" + gradeAvg)
            # print("评论总数:" + rateTotal)
            # print("商品名:" + title)
            # print("连接:" + link)
            # print("销售量:" + sales)
            # print("价格:" + price)
            # print("地址:" + loc)
            itemId.append(id)
            sellerId.append(uid)
            titles.append(title)
            comment_file = open(‘商品.csv‘, ‘a‘, newline=‘‘)
            write = csv.writer(comment_file)
            write.writerow([title, link, sales, price, loc,gradeAvg,rateTotal])
            comment_file.close()
    except (req.ConnectionError, IndexError, UnicodeEncodeError, TimeoutError) as e:
        print(e.args)
    except response.URLError as e:
        print(e.reason)
    except IOError as e:
        print(e)
    # HTTPError
    except response.HTTPError as e:
        print(e.code)
    print("商品基本信息收集完毕")

def get_product_comment():
# 具体商品获取评论
# 前十销量商品
    global title
    for i in range(10):
        print("正在收集第{}件商品评论".format(str(i + 1)))
        for j in range(1,551):
            # 商品评论的url
            detaillinks="https://rate.tmall.com/list_detail_rate.htm?itemId="+itemId[i]+"&sellerId="+sellerId[i]+"&currentPage="+str(j)
            head = {}
            # 写入User Agent信息
            head[‘User-Agent‘] = ‘Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19‘
            req1 = request.Request(detaillinks, headers=head)
            # 传入创建好的Request对象
            response1 = request.urlopen(req1,timeout=30)
            # 读取响应信息并解码
            html1 = response1.read().decode(‘gbk‘)
            # 打印信息
            # 评论
            rateContent = ‘"rateContent":"(.*?)"‘
            # 时间
            rateDate = ‘"rateDate":"(.*?)"‘
            # 颜色
            auctionSku = ‘"auctionSku":"(.*?)"‘
            all_date = re.compile(rateDate).findall(html1)
            all_content = re.compile(rateContent).findall(html1)
            all_sku = re.compile(auctionSku).findall(html1)
            # 获取全部评论
            try:

                for k in range(0, len(all_content)):
                    this_date = all_date[k]
                    this_content = all_content[k]
                    this_sku = all_sku[k]
                    date = str(this_date)
                    content = str(this_content)
                    sku = str(this_sku)
                    # print("时间:" + date)
                    # print(sku)
                    # print("评价:" + content)
                    productfile = open(‘评价.csv‘, ‘a‘, newline=‘‘)
                    product_write = csv.writer(productfile)
                    product_write.writerow([itemId[i] + "\t", titles[i], date, sku, content])
                    productfile.close()
            except (req1.ConnectionError, IndexError, UnicodeEncodeError, TimeoutError) as e:
                print(e.args)
            # URLError产生的原因:网络无连接,即本机无法上网;连接不到特定的服务器;服务器不存在
            except response1.URLError as e:
                print(e.reason)
            # HTTPError
            except response1.HTTPError as e:
                print(e.code)
            except IOError as e:
                print(e)
        print("第{}件商品评论收集完成".format(str(i+1)))

if __name__ == "__main__":
    start=time.time()
    get_product_info()
    get_product()
    # get_product_comment()
    end=time.time()
    total=end-start
    print(‘本次爬行用时:{:.2f}s!‘.format(total))
from urllib import request
import re
import csv
import time
itemId=[]
sellerId=[]
links=[]
titles=[]
# ,‘商品评分‘,‘评论总数‘
def get_product_info():
    fileName = ‘商品.csv‘
    comment_file = open(fileName, ‘w‘, newline=‘‘)
    write = csv.writer(comment_file)
    write.writerow([‘商品名‘, ‘连接‘, ‘销售量‘, ‘价格‘, ‘地址‘,‘商品评分‘,‘评论总数‘])
    comment_file.close()

    fileName2 = ‘评价.csv‘
    productfile = open(fileName2, ‘w‘, newline=‘‘)
    product_write = csv.writer(productfile)
    product_write.writerow([‘商品id‘,‘商品名‘,‘时间‘, ‘颜色分类‘, ‘评价‘])
    productfile.close()

def get_product():
    global itemId
    global sellerId
    global titles
    url = ‘https://s.taobao.com/search?q=%E5%8F%A3%E7%BA%A2&sort=sale-desc‘
    head = {}
    # 写入User Agent信息
    head[
        ‘User-Agent‘] = ‘Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19‘
    # 创建Request对象
    req = request.Request(url, headers=head)
    # 传入创建好的Request对象
    response = request.urlopen(req, timeout=30)
    # 读取响应信息并解码
    html = response.read().decode(‘utf-8‘)
    # 打印信息
    pattam_id = ‘"nid":"(.*?)"‘
    raw_title = ‘"raw_title":"(.*?)"‘
    view_price = ‘"view_price":"(.*?)"‘
    view_sales = ‘"view_sales":"(.*?)"‘
    item_loc = ‘"item_loc":"(.*?)"‘
    user_id = ‘"user_id":"(.*?)"‘
    all_id = re.compile(pattam_id).findall(html)
    all_title = re.compile(raw_title).findall(html)
    all_price = re.compile(view_price).findall(html)
    all_sales = re.compile(view_sales).findall(html)
    all_loc = re.compile(item_loc).findall(html)
    all_userid = re.compile(user_id).findall(html)
    print("开始收集信息")
    try:
        for i in range(10):
            this_id = all_id[i]
            this_title = all_title[i]
            this_price = all_price[i]
            this_sales = all_sales[i]
            this_loc = all_loc[i]
            this_userid = all_userid[i]
            id = str(this_id)
            title = str(this_title)
            price = str(this_price)
            sales = str(this_sales)
            loc = str(this_loc)
            uid = str(this_userid)
            link = ‘https://item.taobao.com/item.htm?id=‘ + str(id)
            shoplink = ‘https://dsr-rate.tmall.com/list_dsr_info.htm?itemId=‘ +str(id)
            head = {}
            # 写入User Agent信息
            head[
                ‘User-Agent‘] = ‘Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19‘
            # 创建Request对象
            req2 = request.Request(shoplink, headers=head)
            # 传入创建好的Request对象
            response2 = request.urlopen(req2, timeout=30)
            # 读取响应信息并解码
            html2 = response2.read().decode(‘utf-8‘)
            gradeAvg = ‘"gradeAvg":(.*?,)"‘
            rateTotal = ‘"rateTotal":(.*?,)"‘
            all_gradeAvg = re.compile(gradeAvg).findall(html2)
            all_rateTotal = re.compile(rateTotal).findall(html2)
            this_gradeAvg = all_gradeAvg
            this_rateTotal = all_rateTotal
            gradeAvg = str(this_gradeAvg)[2:-3]
            rateTotal = str(this_rateTotal)[2:-3]
            # print("平均分:" + gradeAvg)
            # print("评论总数:" + rateTotal)
            # print("商品名:" + title)
            # print("连接:" + link)
            # print("销售量:" + sales)
            # print("价格:" + price)
            # print("地址:" + loc)
            itemId.append(id)
            sellerId.append(uid)
            titles.append(title)
            comment_file = open(‘商品.csv‘, ‘a‘, newline=‘‘)
            write = csv.writer(comment_file)
            write.writerow([title, link, sales, price, loc,gradeAvg,rateTotal])
            comment_file.close()
    except (req.ConnectionError, IndexError, UnicodeEncodeError, TimeoutError) as e:
        print(e.args)
    except response.URLError as e:
        print(e.reason)
    except IOError as e:
        print(e)
    # HTTPError
    except response.HTTPError as e:
        print(e.code)
    print("商品基本信息收集完毕")

def get_product_comment():
# 具体商品获取评论
# 前十销量商品
    global title
    for i in range(10):
        print("正在收集第{}件商品评论".format(str(i + 1)))
        for j in range(1,551):
            # 商品评论的url
            detaillinks="https://rate.tmall.com/list_detail_rate.htm?itemId="+itemId[i]+"&sellerId="+sellerId[i]+"&currentPage="+str(j)
            head = {}
            # 写入User Agent信息
            head[‘User-Agent‘] = ‘Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19‘
            req1 = request.Request(detaillinks, headers=head)
            # 传入创建好的Request对象
            response1 = request.urlopen(req1,timeout=30)
            # 读取响应信息并解码
            html1 = response1.read().decode(‘gbk‘)
            # 打印信息
            # 评论
            rateContent = ‘"rateContent":"(.*?)"‘
            # 时间
            rateDate = ‘"rateDate":"(.*?)"‘
            # 颜色
            auctionSku = ‘"auctionSku":"(.*?)"‘
            all_date = re.compile(rateDate).findall(html1)
            all_content = re.compile(rateContent).findall(html1)
            all_sku = re.compile(auctionSku).findall(html1)
            # 获取全部评论
            try:

                for k in range(0, len(all_content)):
                    this_date = all_date[k]
                    this_content = all_content[k]
                    this_sku = all_sku[k]
                    date = str(this_date)
                    content = str(this_content)
                    sku = str(this_sku)
                    # print("时间:" + date)
                    # print(sku)
                    # print("评价:" + content)
                    productfile = open(‘评价.csv‘, ‘a‘, newline=‘‘)
                    product_write = csv.writer(productfile)
                    product_write.writerow([itemId[i] + "\t", titles[i], date, sku, content])
                    productfile.close()
            except (req1.ConnectionError, IndexError, UnicodeEncodeError, TimeoutError) as e:
                print(e.args)
            # URLError产生的原因:网络无连接,即本机无法上网;连接不到特定的服务器;服务器不存在
            except response1.URLError as e:
                print(e.reason)
            # HTTPError
            except response1.HTTPError as e:
                print(e.code)
            except IOError as e:
                print(e)
        print("第{}件商品评论收集完成".format(str(i+1)))

if __name__ == "__main__":
    start=time.time()
    get_product_info()
    get_product()
    # get_product_comment()
    end=time.time()
    total=end-start
    print(‘本次爬行用时:{:.2f}s!‘.format(total))

  

时间: 2024-08-30 13:50:41

一个完整的大作业:淘宝口红销量top10的销量和评价的相关文章

一个完整的大作业--广州市社会保障(市民)卡服务网

1.选一个自己感兴趣的主题. 广州市社会保障(市民)卡服务网,网页网址为http://card.gz.gov.cn/gzshbzk/xwgg/list_2.shtml 2.网络上爬取相关的数据. import requests from bs4 import BeautifulSoup from datetime import datetime import re # 爬取单条资讯的信息 def getTheContent(url1): res = requests.get(url1) res.

一个完整的大作业

用Python写的百度贴吧的网络爬虫. 1.使用方法: 新建一个BugBaidu.py文件,然后将代码复制到里面后,双击运行. 2.程序功能: 将贴吧中楼主发布的内容打包txt存储到本地. 3.原理解释: 首先,先浏览一下某一条贴吧,点击只看楼主并点击第二页之后url发生了一点变化,变成了:http://tieba.baidu.com/p/2296712428?see_lz=1&pn=1可以看出来,see_lz=1是只看楼主,pn=1是对应的页码,记住这一点为以后的编写做准备.这就是我们需要利用

大数据 -->淘宝异构数据源数据交换工具 DataX

淘宝异构数据源数据交换工具 DataX DataX是什么? DataX是一个在异构的数据库/文件系统之间高速交换数据的工具,实现了在任意的数据处理系统(RDBMS/Hdfs/Local filesystem)之间的数据交换,由淘宝数据平台部门完成. DataX用来解决什么? 目前成熟的数据导入导出工具比较多,但是一般都只能用于数据导入或者导出,并且只能支持一个或者几个特定类型的数据库.这样带来的一个问题是,如果我们拥有很多不同类型的数据库/文件系统(Mysql/Oracle/Rac/Hive/O

做大数据时代的“淘宝”平台,IBM数据分析战略浮出水面

(上图为IBM研究人员在展示通过数据分析提高城市交通水平) 下个世纪是大数据的世纪,是从IT走向认知计算的时代.在IT时代成就了一家超级平台,这就是淘宝,而认知时代要做的是数据的生意,那是否有一个类似淘宝的超级数据平台呢?IBM正在做这件事情. IBM在全球布局了40多个基于Softlayer的数据中心,以Bluemix作为其主力云端开发平台, 在之上通过合作和收购网罗了从Twitter到The Weather Company以及这些年投入250亿美金收购的Cognos.SPSS.ILOG.Al

淘宝杨志丰:OceanBase--淘宝结构化大数据解决之道

时至今日,“Big data”(大数据)时代的来临已经毋庸置疑,尤其是在电信.金融等行业,几乎已经到了“数据就是业务本身”的地步.这种趋势已经让很多相信数据之力量的企业做出改变.恰逢此时,为了让更多的人了解和使用分析大数据,CSDN独家承办的大数据技术大会于今日在北京中旅大厦召开.本次大会汇集Hadoop.NoSQL.数据分析与挖掘.数据仓库.商业智能以及开源云计算架构等诸多热点话题.包括百度.淘宝.新浪等业界知名专家与参会者齐聚一堂,共同探讨大数据浪潮下的行业应对法则以及大数据时代的抉择. 淘

浅谈android中仅仅使用一个TextView实现高仿京东,淘宝各种倒计时

今天给大家带来的是仅仅使用一个TextView实现一个高仿京东.淘宝.唯品会等各种电商APP的活动倒计时.最近公司一直加班也没来得及时间去整理,今天难得休息想把这个分享给大家,只求共同学习,以及自己后续的复习.为什么会想到使用一个TextView来实现呢?因为最近公司在做一些优化的工作,其中就有一个倒计时样式,原来开发的这个控件的同事使用了多个TextView拼接在一起的,实现的代码冗余比较大,故此项目经理就说:小宏这个就交给你来优化了,并且还要保证有一定的扩展性,当时就懵逼了.不知道从何处开始

浅谈android中只使用一个TextView实现高仿京东,淘宝各种倒计时

今天给大家带来的是只使用一个TextView实现一个高仿京东.淘宝.唯品会等各种电商APP的活动倒计时.近期公司一直加班也没来得及时间去整理,今天难得歇息想把这个分享给大家.只求共同学习,以及自己兴许的复习. 为什么会想到使用一个TextView来实现呢?由于近期公司在做一些优化的工作,当中就有一个倒计时样式,原来开发的这个控件的同事使用了多个TextView拼接在一起的.实现的代码冗余比較大.故此项目经理就说:小宏这个就交给你来优化了.而且还要保证有一定的扩展性,当时就懵逼了.不知道从何处開始

你刚在淘宝上买了一件衣服---详细解析技术流程(淘宝首页显示一个页面的过程)

声明:文章是之前在网络中看到并保存在电脑里的文档,原地址也无从找到.在此声明.向互联网工程师致敬! 你发现快要过年了,于是想给你的女朋友买一件毛衣,你打开了www.taobao.com.这时你的浏览器首先查询DNS服务器,将www.taobao.com转换成ip地址.不过首先你会发现,你在不同的地区或者不同的网络(电信.联通.移动)的情况下,转换后的IP地址很可能是不一样的,这首先涉及到负载均衡的第一步,通过DNS解析域名时将你的访问分配到不同的入口,同时尽可能保证你所访问的入口是所有入口中可能

淘宝等seo广告里面所讲的三天上首页的快排技术大揭秘

淘宝等seo广告里面所讲的三天上首页的快排技术大揭秘 淘宝seo快排技术 今天,我在志在指尖群里面看了看,有人说做一个排名其实非常的简单(我去,简单?想做好seo这是何等漫长的一个事情,谈何简单)我们都知道,做好seo,不仅要做好站内,也要做好站外,不管是关键词布局,内链布局等,还是外链创设,在这是文章书写等,这都是需要很大耐心以及技术的.所以,我没打扰他,我就想听听他口中所谓seo'简单'二字是什么意思,结果意想不到,他就直说了四个字-淘宝快排-what fuck?这四个字让我笑得肚子疼(这里