python 抓取接口数据 ————网站图片---ajax链接地址图片 爬京东图片

网站页面分为静态页面和动态页面,动态页面有分很多类,本篇主要是抓取的京东的https://miaosha.jd.com/category.html?cate_id=19链接(为什么不抓淘宝,因为淘宝做了些验证措施,如果验证未通过,跳转登录页面,有跳过验证的文章可以分享给我(* ̄︶ ̄))京东店的页面是通过ajax请求,然后渲染页面

打开页面通过network 查看接口,可以看到一个接口https://ai.jd.com/index_new?app=Seckill&action=pcSeckillCategoryGoods&callback=pcSeckillCategoryGoods&id=19&_=1545027708656

返回的数据应该是主要数据。

接下来就是通过这个接口来取其中的图片

直接贴代码,代码很详细

import requests
from bs4 import BeautifulSoup
import urllib
import json
import os
#下载功能
def download(img_url,headers):
    req = requests.get("http:"+img_url, headers=headers)
    name = img_url
    name=name.replace("/","\\")#因为的是window,把/换成\
    
    path = r'C:'#s设置一个底层路径
    file_name = path  + name
    indexa=file_name.rfind('\\')
    print(indexa)
    #print(file_name.rfind("\\"))
    #print(file_name)
    print(type(file_name));
    filepath=file_name[0:indexa+1];
    print(filepath);
    print(os.path.exists(filepath))
        
    if(os.path.exists(filepath)):#判断文件路径是否存在如果不存在就穿件文件路径在写入
        print("true11");
        f = open(file_name, 'wb')
        f.write(req.content)
        
    else:
        
        os.makedirs(filepath);
        print(os.path.exists(filepath));
        if(os.path.exists(filepath)):
            print(filepath);
            f = open(file_name, 'wb')
            f.write(req.content)
          

    f.close

#打开一个文件准备上传
def writeIn(txtfile,contain):
    
    try:
        #if(os.path.exists(txtfile)):
            
        fobj=open(txtfile,'w') #打开txtFile文件此处   w:      直接打开一个文件,如果文件不存在则创建文件               # 这里的a意思是追加,这样在加了之后就不会覆盖掉源文件中的内容,如果是w则会覆盖。a:以追加模式打开 (从 EOF 开始, 必要时创建新文件)
        #else:
           # os.makedirs(txtfile);
    except IOError:
        print ('*** file open error create')
        
    else:
        fobj.write(contain)
        fobj.close()
    print ("注入数据结束");
  
   
response = urllib.request.urlopen('https://ai.jd.com/index_new?app=Seckill&action=pcSeckillCategoryGoods&callback=pcSeckillCategoryGoods&id=19&_=1545016559723')
#print(response.read());
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"}

aaajson=response.read();#读取数据
result=str(aaajson, encoding = "utf-8")#转utf-8
resultJsonStr=result[23:(result.rfind(')'))]#由于请求到的数据是pcSeckillCategoryGoods(json)的格式需要把pcSeckillCategoryGoods(和)去掉
print(resultJsonStr[0:110])#看数据截取头部{
print(resultJsonStr[len(resultJsonStr)-100:len(resultJsonStr)])#看数据截取尾部是否正确}

resultJsonDict=json.loads(resultJsonStr)## 对数据进行解码
print(type(resultJsonDict))#<class 'dict'>字典类型
resultJsonList=resultJsonDict['goodsList'];
print(type(resultJsonList))#<class 'list'>
print(resultJsonList[0]);#打印第一个数据
"""
{'sourceValue': '13325860722_抢购中_1',
'wname': '【次日达包邮 充电款】Meilen电子秤称重人体秤精准电子称家用计体重秤 USB充电版黑色',
'miaoSha': 'true', 'isNewGoods': 0, 'startRemainTime': -6173,
'spuId': '10462747607', 'seckillNum': '2000', 'jdPrice': '99', 'soldRate': 34, 'startTimeContent': '', 'endTime': 1545098399000,
'brandId': 0, 'startTimeShow': '10:00', 'promotionId': '15477982159', 'startTime': 1545012000000, 'tagType': None, 'miaoShaPrice': '49',
'endRemainTime': 80226, 'tagText': None, 'startTimeMills': 1545012000000,
'imageurl': '//m.360buyimg.com/mobilecms/s210x210_jfs/t26761/196/2461771515/54423/90816f8b/5c02334eNc57d565d.jpg!q70.jpg',
'wareId': '13325860722', 'almostSoldoutViewUser': 1}
"""

""" 将json保存到文件中"""

writeIn("jsonfile.json",str(resultJsonList));#将数据保存
""" json保存结束"""
print(resultJsonList[10]["imageurl"]);#打印图片地址数据
for i in range(0,len(resultJsonList)-1):
    imgUrl=resultJsonList[i]["imageurl"]
    #if(i==10):#测试使用
        #print(imgUrl)
        #download(imgUrl,headers);
    download(imgUrl,headers);
   

print("结束")
    

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值