python+json爬虫

#你们看到过最丧的句子是什么?#
5039条回答
筛选收录共661条数据
用时:488.5270941257477 s

h00 环境准备

	python 3.6
	import requests
	import json
	import time
	import re

h01 第三方库:json

json 一种轻量级的数据交换格式,易于人阅读和编写
举个例子,平时我们在查看网页原始数据的时候,格式是这样的
在这里插入图片描述当我们用json查看的时候是这样的,当我们获取这个链接的时候,返回的是一个字典,我们可以对这个字典进行数据的读取操作,具体信息还得查阅相关专业文档
在这里插入图片描述这里主要用到的是json.loads,功能是将已编码的 JSON 字符串解码为 Python 对象,之后就可以对这个对象进行直接的处理

h02 核心代码

def get_url(url):
headers = {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
}

try:
    r = requests.get(url, headers=headers)
    r.raise_for_status()
    return r.text

except:
    print("获取链接失败")

主要功能:获取网页的内容数据

def save(dataa):
    global num
    st1 = "%s:  %s \n" % (num,dataa)
    try:
        with open(r'318185970.txt','a') as f:
            f.write(st1)
        num=num+1
    except:
        print("文件打开或者写入出错")

主要功能:接收传输过来的数据并把他保存到 318185970.txt 这个文档中,num是给保存到文档中的句子标号

def url_data(html):
    json_data = json.loads(html)['data']   
    try:
        for i in json_data:
            p = re.compile(r"te>+(.*?[<])")
            a=p.findall(i['content'])
            for ii in a:
                if ii == '<':
                    pass
                elif '<' in ii:
                    ii = ii.replace('<','')
                    if len(ii) <= 100:
                        print(str(ii))
                        totalnum=totalnum+1
                        save(ii)
                else:
                    print(ii)
    except:
        print("出错!!!")

主要功能:提取网页数据中的关键信息,即回答。我这里使用了正则表达式来提取(正则表达式构造的不是很好),然后调取save函数进行保存文档

def main():
    global totals,question
    url = 'https://www.zhihu.com/api/v4/questions/318185970/answers?include=data%5B%2A%5D.is_normal%2Cadmin_closed_comment%2Creward_info%2Cis_collapsed%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Crelevant_info%2Cquestion%2Cexcerpt%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cis_labeled%3Bdata%5B%2A%5D.mark_infos%5B%2A%5D.url%3Bdata%5B%2A%5D.author.follower_count%2Cbadge%5B%2A%5D.topics&limit=5&offset=5&platform=desktop&sort_by=default'
    
    html = get_data(url)
    totals = json.loads(html)['paging']['totals']   #获取回答的总数
    question = json.loads(html)['data'][0]['question']['title']     #获取问题

    page = 0
    while(page < totals):
        print("====>正在翻页...")
        url = 'https://www.zhihu.com/api/v4/questions/318185970/answers?include=data%5B%2A%5D.is_normal%2Cadmin_closed_comment%2Creward_info%2Cis_collapsed%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Crelevant_info%2Cquestion%2Cexcerpt%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cis_labeled%3Bdata%5B%2A%5D.mark_infos%5B%2A%5D.url%3Bdata%5B%2A%5D.author.follower_count%2Cbadge%5B%2A%5D.topics&limit=5&offset='+ str(page) +'&platform=desktop&sort_by=default'
        html = get_data(url)
        url_data(html)
        print(page)
        page += 5

主要功能:访问网页并把网页数据传给url_data函数

h03 运行结果
在这里插入图片描述在这里插入图片描述
在这里插入图片描述
h04 筛选数据原则

回答少于100个字符的筛选掉,我们查看网页源代码,段落内容包含在<p></p>标签中,
每一句话的内容包含在<b></b>中,然后使用正则表达式把标签里面的内容都提取出来进行筛选

h05 什么是 AJAX ?

AJAX = 异步 JavaScript 和 XML。
AJAX 是一种用于创建快速动态网页的技术。
通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。
这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。

网页版的知乎用的就是这么一个技术

h 结束语

	终于在放假后的空闲时间里把这个弄出来了,之前有个小伙伴叫我写个爬虫爬一下数据(很多条),
当时的我只会requests,不好意思答应下来,能力不够绝不会轻易答应,放假的时间里,用知乎来练手,
学习新的库和复习。正则表达式这块忘的太多了,美丽汤也许更好,但我还是选择了正则表达式来完成。
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值