爬虫初学8——cookie爬淘宝列表

转载——实测可用

# //get_goods_from_taobao
#现在淘宝只能登陆之后才能搜索,所以本次介绍的是登录获取cookie之后的操作。
import requests #库
import re   #正则
import xlsxwriter   #写入excel

#不要爬取太多,小心被封 发布的时候注释掉
cok = ''  # 此处写入登录之后自己的cookie

'''# 获取页面'''
def getHTMLText(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'}
    usercookies = cok
    cookies = {}
    for a in usercookies.split(';'):
        name, value = a.strip().split('=', 1)   #分割一次,分别保存到两个文件中
        cookies[name] = value
    try:#这个代码中我们用r.raise_for_status()方法,它就可以有效的判断网络连接的状态。如果网连接出现错误,那么它就会用try-except来获取一个异常。而这个异常,在异常部分,我们用了一句 return “产生异常” 来表示,我们捕获到了这个异常,所以这样一个通用代码框架可以有效的处理,我们在访问或爬取网页过程中,它可能出现的一些错误,或者是网络不稳定造成的一些现象
        r = requests.get(url, cookies=cookies, headers=headers, timeout=60) #设置时间限制
        r.raise_for_status()
        r.encoding = r.apparent_encoding    #r.encoding 从HTTP header中猜测的响应内容编码方式(r.apparent_encoding 从内容中分析出的响应内容编码方式(备选编码方式)
        return r.text
    except:
        return ''

'''#  格式化页面,查找数据'''
def parsePage(ilt, html):
    try:
        print('爬取成功')
        plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"', html)
        tlt = re.findall(r'\"raw_title\"\:\".*?\"', html)
        for i in range(len(plt)):
            price = eval(plt[i].split(':')[1])  #返回表达式结果,列表是列表,字典是字典
            title = eval(tlt[i].split(':')[1])
            ilt.append([price, title])
    except:
        print('')

'''#  打印数据列表'''
def printGoodList(ilt):
    tplt = '{:4}\t{:8}\t{:16}'  #\t表示空四个字符,也称缩进,相当于按一下Tab键  #1、{0:30}中的0是一个序号,表示格式化输出的第0个字符,依次累加;2、{0:30}中的30表示输出宽度约束为30个字符;
    # print(tplt.format('序号', '价格', '名称'))   #print'hello{0} i am {1}'.format('Kevin','Tom')                  #hello Kevin i am Tom
    count = 0
    for c in ilt:
        count = count + 1
        print(tplt.format(count, c[0], c[1]))

'''#  写入excel'''
def writetoexcel(list):
    print('开始创建excel表格')
    book = xlsxwriter.Workbook(u'淘宝数据.xlsx')    #u?
    sheet = book.add_worksheet()
    sheet.write(0, 0, '序号')
    sheet.write(0, 1, '名称')
    sheet.write(0, 2, '价格')
    row = 1
    col = 0
    for index, item in enumerate(list):
        print('写入第%s行数据' % row)
        sheet.write(row, col, index + 1)  # 写入序号值
        sheet.write(row, col + 1, item[1])  # 写入名称
        sheet.write(row, col + 2, item[0])  # 写入价格
        row += 1
    print('写入完成')
    book.close()  # 关闭
    
def main():
    goods = input('请输入想查询的内容:'.strip())  # 输入想搜索的商品名称   #在我们使用input的时候,会从标准输入中读取一个string,即字符串(请注意,这里很重要,下面我们会继续说),对于用户输入的换行是不会读入的,因为我们都知道input是以换行作为输入结束的标志的。
    depth = 3  # 爬取的页数
    start_url = 'http://s.taobao.com/search?q=' + goods  # 搜索接口地址
    infoList = []
    for i in range(depth):
        try:
            page = i + 1
            print('正在爬取第%s页数据' % page)
            url = start_url + '&s=' + str(44 * i)   #这种搜索方式挺好
            print(url)
            html = getHTMLText(url)
            parsePage(infoList, html)
        except:
            continue
    printGoodList(infoList)
    writetoexcel(infoList)
main()

博主:前端的小小对象
原文链接:https://blog.csdn.net/a736755244/article/details/103351817

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值