文章目录

    • 前言
    • 简单需求分析
    • 技术点
    • 代码实现

前言

前面两篇内嵌在“我要偷偷学Python”系列里面了,等我抽出手来就去分离出来。

一直挂在别的系列下也不好,想了想,独立出来吧。

简单需求分析

爬取蝉妈妈上的热门商品信息。https://www.chanmama.com/

技术点

登录后爬取页面信息,爬取过程中涉及到页面的跳转,对数据的清洗与存储。

后面的就没什么好说了,清洗与存储在第二战中展现,页面跳转,页面跳转,在讲Xpath的时候有展现,这里再做一次。
登录之后爬取页面信息倒是第一次做。

过了这个槛,可以玩的东西又多了很多。
广阔天地,大有可为。

这里的代码由我们“爬虫百战穿山甲”小分队里的“垍”同学独立完成。

非常之强,晚上六点的时候我把需求放到群里,晚上八点他就解决了,实实在在的惊呆了我们所有人。

代码实现

来看看不同风格的代码:

import requests,time
def cook(t):#取登陆前COOKIE
    url="https://www.chanmama.com/login"
    res = requests.get(url,headers=h)  
    w = res.text.find('https://hm.baidu.com/hm.js?')+27
    c = res.text[w:w+32]
    co = { 'Hm_lvt_'+c: t, 'Hm_lpvt_'+c:t}
    #print(w,c,co)
    return(co)

def login(user,password):#登陆并手动更新COOKIE
    url = "https://api-service.chanmama.com/v1/access/token"
    d = '{"appId":10000,"timeStamp":'+t+',"username":"'+user+'","password":"'+password+'"}'
    res = requests.post(url, data=d, headers=h, cookies=c)
    data = res.json()
    if data['errCode']==0:
        c['LOGIN-TOKEN-FORSNS'] = data['data']['token']
        h['Authorization'] = data['data']['token']
        print('登陆成功~~')
        return(True)
    else:
        print('登陆失败~~')
        return(False)

def pa(aa,s):#爬出源码
    url = "https://api-service.chanmama.com/v1/product/search"
    d = { "keyword":aa,"keyword_type":"","page":1,"price":"","size":s,"filter_coupon":0,"is_aweme_goods":0,"has_live":0,"has_video":0,"tb_max_commission_rate":"","day_pv_count":"","day_order_count":"","big_category":"","first_category":"","second_category":"","platform":"","sort":"day_order_count","order_by":"desc"}
    res = requests.post(url,json = d,headers=h,cookies=c)
    save(res.json())

def save(tt):#保存信息
    with open(r'在你自己的电脑上弄个文件','w+',encoding='utf-8') as fo:
        for i in tt['data']['list']:        
            print("商品:%s 价格:%s 原价:%s 昨日浏览:%s 昨日销量:%s" %(i['title'],i['price'],i['market_price'],i['day_pv_count'],i['day_order_count']))
            fo.write("商品:%s 价格:%s 原价:%s 昨日浏览:%s 昨日销量:%s\n" %(i['title'],i['price'],i['market_price'],i['day_pv_count'],i['day_order_count']))    

h = { "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"}
t = str(int(time.time()))
c = cook(t)

if login('填你的账号','填你的密码'):
    pa('商品自己选',50)#非VIP只可以取前50条
    #这里填入商品和要爬取的数据条数

强!!!!!

本文地址:https://blog.csdn.net/qq_43762191/article/details/110522448