首页 新闻 会员 周边

python爬虫的一个问题,json.loads()不能转化字符串为dict类型

0
[待解决问题]

现在要爬取出网页html里面的url,做法是:
1,用正则把gallery: JSON.parse()这个括号里面的内容先匹配出来也就是:
str= images_pattern=re.compile(r'gallery: JSON.parse((.*?)),',re.S) result=re.findall(images_pattern,html)[0]
2,把取出来的字符串用json.loads()转化成一个字典:
data=json.loads(result)
3再用for遍历字典里面的key,取出url:
if data and "sub_images" in data.keys():
sub_images=data.get('sub_images')
url=[item.get('url') for item in sub_images]
奇怪的是这里第二步得到的还是一个字符串类型,然后我自己测试了一下:
import json
html="{"count":6,"sub_images":"http:\\/\\/pb3.pstatp.com\"}"
print('原来的data类型....',type(html))
data=json.loads(html)print(type(data),data)
运行结果:原来的data类型.... <class 'str'>
<class 'dict'> {'count': 6, 'sub_images': 'http://pb3.pstatp.com'}
这是为啥呢?同样是字符串,为什么我测试的代码里面可以把字符串转化为字典,但是这里就不行呢,反而在第二部下面再加个data=json.loads(data)就可以转化为字典了,也就是用两次json.loads,第一次学爬虫,望知道的不吝赐教,谢谢了

cfRobotLab的主页 cfRobotLab | 菜鸟二级 | 园豆:202
提问于:2018-10-31 20:07
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册