QQ空间Python爬虫(2)---分析json

我们把上一篇访问得到的json数据拿来先分析一下,这里需要借助json解析工具,推荐json.cn:

观察图片右边,具体的分析过程不再赘述了,我们发现图片url信息在 date-->vFeeds(list)-->pic-->picdata-->pic(list)-->photourl-->0-->url 中(其中的list注意循环处理一下)

文字信息在date-->vFeeds(list)-->summary-->summary中,代码如下:

 1 url_x = 'https://mobile.qzone.qq.com/list?qzonetoken=30168ded82ff81d41e518db8ef77b00b94375b2139f956165128f52dd25c322e603e03f180d761dc42881f1a83e9&g_tk=420005040&res_attach=att%3D'
 2 url_y = '%26tl%3D1508148135&format=json&list_type=shuoshuo&action=0&res_uin=627911861&count=40'
 3 numbers = 0      # ‘查看更多’翻页
 4 img_set = set()  # 存放图片url集
 5 word_count = 0   # 文字说说计数器
 6 words = ""       # 存放文字说说
 7 images = ""      # 存放图片url
 8 page = int(1758 / 40)
 9 
10 # for i in range(0, 43):
11 try:
12     html = requests.get(url_x + str(numbers) + url_y, headers=headers).content
13     data = json.loads(html)
14 
15     for vFeed in data['data']['vFeeds']:
16         if 'pic' in vFeed:
17             for pic in vFeed['pic']['picdata']['pic']:
18                 img_set.add(pic['photourl']['0']['url'])
19 
20         if 'summary' in vFeed:
21             # print(str(word_count) + '. ' + vFeed['summary']['summary'])
22             words += str(word_count) + '. ' + vFeed['summary']['summary'] + '
'
23             word_count += 1
24 
25 except:
26     print('error')

上面之所以要把url拆成两段是为了处理变量,因为url存在%字符,用%s,%d来处理比较麻烦(懒得研究-。-)

(此处代码仅仅爬取了40条说说信息,先测试跑通,后面再做爬取所有说说的循环处理)

接下来,就可以将爬取到的文字与图片信息分别写入文件了,文字可以直接写成文本文件,图片为url集合先写入文件再做下载处理:

 1 try:
 2     with open(os.getcwd() + '\' + str(qq) + '.txt', 'wb') as fo:
 3         fo.write(words.encode('utf-8'))
 4         print("文字说说写入完毕")
 5 
 6     with open(os.getcwd() + '\' + 'images_url', 'wb') as foImg:
 7         for imgUrl in img_set:
 8             images += imgUrl + '
'
 9         foImg.write(images.encode('utf-8'))
10         print("图片写入完毕")
11 
12 except:
13     print('写入数据出错')

多次请求之后会发生登陆的问题,后面再描述。不过,json数据分析的部分至此已经完成了。

下一章:

QQ空间Python爬虫(3)---终章

原文地址:https://www.cnblogs.com/neilshi/p/7879935.html