某些情况下json.loads报错的问题

版权声明:为NH4L所有,转载请注明 https://blog.csdn.net/LeeGe666/article/details/81362884

这是今日头条上ajax中一个有关于图片信息的变量:

gallery: JSON.parse("{\"count\":6,\"sub_images\":[{\"url\":\"http:\\/\\/p3.pstatp.com\\/origin\\/pgc-image\\/153311418372487f65e2a82\",\"width\":690,\"url_list\":[{\"url\":\"http:\\/\\/p3.pstatp.com\\/origin\\/pgc-image\\/153311418372487f65e2a82\"}······

分析ajax并获取gallery中的图片信息,由于今日头条网站的更新,以前的分析代码不管用了,
下面是用正则获取其中的字符串,特别要注意()的表示方式,前面要加\

images_pattern = re.compile('gallery: JSON.parse\("(.*?)"\)',re.S)
result = re.search(images_pattern,html)
    if result:
        str = re.sub(r'(\\)', '', result.group(1))
        data = json.loads(str)
        if data and 'sub_images' in data.keys():
            sub_images = data.get('sub_images')
            images = [item.get('url') for item in sub_images]
            return {
                'title':title,
                'url':url,
                'images':images
            }

今日头条如今加了一些简单的反扒机制,比以前直接给出来要麻烦的,所以上面有re.sub将字符串中的所以\替换掉,这样格式正确了之后才能用把字符串格式的转化为json,才可以使用json.loads,进而可以获取图片的打开链接,进而进行下一步爬取。

猜你喜欢

转载自blog.csdn.net/LeeGe666/article/details/81362884