某宝爬取

案例简介

在这里插入图片描述
搜索的首页链接
https://s.taobao.com/search?q=连衣裙&imgfile=&js=1&stats_click=search_radio_all%3A1&initiative_id=staobaoz_20200212&ie=utf8
第二页链接
https://s.taobao.com/search?q=连衣裙&imgfile=&js=1&stats_click=search_radio_all%3A1&initiative_id=staobaoz_20200212&ie=utf8&bcoffset=3&ntoffset=3&p4ppushleft=1%2C48&s=44
第三页
https://s.taobao.com/search?spm=a21bo.2017.201856-fline.1.5af911d9hm0jKA&q=%E8%BF%9E%E8%A1%A3%E8%A3%99&refpid=420460_1006&source=tbsy&style=grid&tab=all&pvid=d0f2ec2810bcec0d5a16d5283ce59f66&bcoffset=0&p4ppushleft=3%2C44&s=88

第二页与第三页的s= 不同正好表示的是商品数

在这里插入图片描述

实例编写

查看页面信息名称和价格
在这里插入图片描述
任何商品的价格是由"view":“price"这一键字对确定
在这里插入图片描述
商品名称前也有一个键
“raw_title”:”【商场同款】太平鸟女装春装2020新款娃娃领绣花连衣裙A1FAA1223"
即"raw_title":“名称”

因此想获得这两个信息,只需要在获得的文本中检索到view_price,和raw_title,并把后续的信息提取出来即可
用正则表达式就十分合适
这个信息虽然在HTML页面中,但它是一种脚本语言的体现,并不是一个完整的HTML页面的表示

#功能描述
#目标:获取淘宝搜索页面信息,提取商品的名称价格
#淘宝的搜索接口,翻页的处理
#技术路线requests-re
# 步骤1:提交商品搜索请求,循环获取页面
# 步骤2:对于每个页面,提取商品名称和价格信息
# 步骤3:将信息输出到屏幕上

import re
import requests
#获得页面
def getHTMLText(url):
    try:
        r=requests.get(url,timeout=30)
        r.raise_for_status()
        r.encoding=r.apparent_encoding
        return r.text
    except:
        return "WRONG!"


#对每一个获得页面进行解析,ilt-结果的列表类型,html-相关HTML页面的信息
def parsePage(ilt,html):
    try:
        #  \表示引入一个"view_price",即首先检索"view_price"字符串,并且获取后面的\d.形成的相关信息
        # 通过这个获得"view_price"和后面的价格,所有获得的信息保存到plt列表中
        plt=re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)
        # *?表示最小匹配
        tlt=re.findall(r'\"raw_title\"\:\".*?\"',html)
        for i in range(len(plt)):
            #使用eval()函数 除去双引号单引号,split函数分割字符串获得键字对的后半部分
            price=eval(plt[i].split(':')[1])
            title=eval(tlt[i].split(':')[1])
            #写入列表中
            ilt.append([price,title])
    except:
        print("wrong")


#将商品信息输出到屏幕上
def printGoodsList(ilt):
    #通过大括号定义槽函数
    #对第1个位置给定长度为4,第2个位置给定长度为8,第3个位置给定长度为16
    tplt="{:4}\t{:8}\t{:16}"
    #打印输出信息的表头
    print(tplt.format("序号","价格","商品名称"))
    #定义计数器count
    count=0
    for g in ilt:
        count=count+1
        print(tplt.format(count,g[0],g[1]))
def main():
    goods="%E8%BF%9E%E8%A1%A3%E8%A3%99"
    #爬取深度
    depth=2
    #通过和goods整合实现对商品的检索
    start_url="https://s.taobao.com/search?q="+goods
    #对输出结果定义变量infoList
    infoList=[]
    for i in range(depth):
        try:
            url=start_url+'&s='+str(44*i)
            html=getHTMLText(url)
            parsePage(infoList,html)
        except:
            continue
    printGoodsList(infoList)


main()
发布了47 篇原创文章 · 获赞 5 · 访问量 1907

猜你喜欢

转载自blog.csdn.net/Pang_ling/article/details/104283096