python的requests库之读取excel中的str转化为字典

最近学习python自动化读取excel中值,使用requests,将url中的headers中的User-Agent修改为特定的值,

读取excel可使用库:pandas

excel如下所示:

case_idtitleurlheader
1使用常规的https://lemon.ke.qq.com/{'User-Agent':'python-requests/2.19.1'}
2修改User-Agent为火狐https://lemon.ke.qq.com/{'User-Agent':'Mozilla/5.0'}
3修改为不存在的https://lemon.ke.qq.com/{'User-Agent':'test'}
4修改为空https://lemon.ke.qq.com/{'User-Agent':''}

初始代码为:

test1.py文件中的
import requests
class HttpRequest:
    def http_request(url,aa):
        req_get=requests.get(url,headers=aa)
        res=req_get.request.headers
        return res
-------------------------------------
test2.py文件中的
import pandas as pd
from test1 import HttpRequest
test_data=pd.read_excel('D:/test.xlsx')#打开excel获取所有的测试
dk=test_data.values

for indexs in dk:
    print("目前执行的是案例{0}:{1}".format(indexs[0],indexs[1]))
    #print(headers)
    res=HttpRequest.http_request(indexs[2],indexs[3])
    print("http的执行结果是{0}".format(res))
    

 执行报错:

原因: excel表中都是str类型,而requests中的headers需要用字典类型,所以需要把excel的第4列进行类型转化

转化方式有两种,一种使用json,一种使用eval(),

使用json,也就是:import json,代码修改如下:

#test2.py文件中的
import pandas as pd
import json
from test1 import HttpRequest
test_data=pd.read_excel('D:/test.xlsx')#打开excel获取所有的测试
dk=test_data.values

for indexs in dk:
    print("目前执行的是案例{0}:{1}".format(indexs[0],indexs[1]))
    aa=json.loads(indexs[3])
    #print(headers)
    res=HttpRequest.http_request(indexs[2],aa))
    print("http的执行结果是{0}".format(res))
    

执行依旧报错:

原因:json中的键值都需要用双引号,所以把excel中的第4列修改为双引号

case_idtitleurlheader
1使用常规的https://lemon.ke.qq.com/{"User-Agent":"python-requests/2.19.1"}
2修改User-Agent为火狐https://lemon.ke.qq.com/{"User-Agent":"Mozilla/5.0"}
3修改为不存在的https://lemon.ke.qq.com/{"User-Agent":"test"}
4修改为空https://lemon.ke.qq.com/{"User-Agent":""}

 可执行成功

 

将str类型修改为字典类型,也有另外的方法,使用eval()方法,例如:eval(indexs[3]),为了确定类型是否成功转化,使用print(type(eval(indexs[3]))),查看是否返回dict

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值