爬虫请求响应以及提取数据2

将爬虫到的数据保存

这里, 我们先将数据保存到文本里面, 至于如何将数据保存到数据库或者excel等操作, 这些我们之后再讲。

其实, 把数据保存到文本里面非常的简单, 思路也很简单, 我们可以创建一个字符串变量, 那个变量就是用于存储爬虫的数据的, 最后我们将数据全部写入文件中。我们就那腾讯招聘的代码为例子。

代码:

python 复制代码
import requests

"""
pageIndex: 查看的数据是第几页数据
"""
page = 1  # 页码
count = 1  # 输出的数据序号
content = '' # 为了存储爬虫的数据所用的变量
# 获取所有数据
while True:
    # 获取1到10页数据
    url = f"https://careers.tencent.com/tencentcareer/api/post/Query?timestamp=1726832959000&countryId=&cityId=&bgIds=&productId=&category=&parentCategory=&attrId=1&keyword=&pageIndex={page}&pageSize=10&language=zh-cn&area=cn"
    res = requests.get(url)
    print(res.text)
    data = res.json()
    # TypeError: 'NoneType' object is not iterable
    # {"Code":200,"Data":{"Count":0,"Posts":null}}
    # 根据数据响应的结果, 进行结束循环的判断
    if data["Data"]['Posts'] is None:
        break
    for i in data["Data"]['Posts']:
        # 岗位名称
        RecruitPostName = i['RecruitPostName']
        # 工作地点
        LocationName = i['LocationName']
        # 工作内容
        Responsibility = i['Responsibility']
        print(count, RecruitPostName, LocationName, Responsibility)
        # 调用操作系统, 打开文件, 往文件中写入数据。
        # 循环多少次, 就打开文件多少次, 效率不高
        # with open("腾讯招聘.txt", "a", encoding="utf-8") as f:
        #     f.write(f"{count}, {RecruitPostName}, {LocationName}, {Responsibility} \n")
        content += f"{count}, {RecruitPostName}, {LocationName}, {Responsibility} \n"
    count += 1
    print(f"第{page}页数据加载完毕")
    page += 1

# 将爬虫爬取到的数据都写到文件里面
with open("腾讯招聘.txt", mode="a", encoding="utf-8") as f:
    f.write(content)

注意:存储数据里面有些细节需要注意一下, 在for循环中, 有一句content += f"{count}, {RecruitPostName}, {LocationName}, {Responsibility} \n", 这句话的content后面必须是+=,而不是=, 这里面我们需要追加数据, 如果是=的话, 那就变成赋值了, 用=会导致只保存最后一条数据, 在最后面\n是换行, 为了保存的数据美观一些而不是挤在一起。还有一点就是, with open("腾讯招聘.txt", mode="a", encoding="utf-8") as f这句话, open函数的mode的值为a, w虽然有写入的模式, 但是会覆盖, 而a代表追加的意思, 这里建议写a。

运行结果:

我们打开腾讯招聘.txt文件


我们发现, 我们成功将爬虫爬取到的数据存入腾讯招聘.txt的文本中了。

实战:
给你一个url, 在那个网站上面进行爬虫
url = https://quote.eastmoney.com/ztb/detail#type=ztgc
找到这个网站数据对应的url发起请求 获取响应数据(解析的字段不限定,随意获取)
注意!!请求参数有一个cb=callbackdataxx 不要携带

提示:
找到网页当中的请求:
1.打开网站(https://quote.eastmoney.com/ztb/detail#type=ztgc), 然后再打开开发者工具f12, 找到网络。

我们发现, 这里面的请求太多了, 根本不能一下子找出来哪个是请求文件, 我们可以用搜索框来搜索我们想要爬取的数据, 然后它就会显示出哪个请求里面会有这个数据。我们随便在网站上面找一个数据进行搜索。
比如我们搜索一个002016, 就是网站的表格当中的第13条数据的其中一个数据。


点击搜索按钮, 输入002016, 按回车, 我们可以发现下面有数据。
点击下面返回的数据, 在右边选择响应。

我们可以发现, 请求就在这个里面。
我们再双击打开这个请求。

我们可以发现返回的是一些后端的数据, 这些后端的数据, 正是我们需要的响应数据。但是我们在最左上面可以发现有个callbackdata7124215, ()里面才是我们想要的数据, 那怎么办呢?
这个很简单, 在题目当中, 就已经告诉我们怎么取操作啦。

所以原本我们的请求url是https://push2ex.eastmoney.com/getTopicZTPool?cb=callbackdata7124215&ut=7eea3edcaed734bea9cbfc24409ed989&dpt=wz.ztzt&Pageindex=0&pagesize=20&sort=fbt%3Aasc&date=20240924&_=1727160924310
但是我们要把cb=callbackdataxxx这个参数去掉, 所以我们的请求最终的url是https://push2ex.eastmoney.com/getTopicZTPool?ut=7eea3edcaed734bea9cbfc24409ed989&dpt=wz.ztzt&Pageindex=0&pagesize=20&sort=fbt%3Aasc&date=20240924&_=1727160924310

先不要马上看答案, 尝试自己做一做哦。

参考答案:

python 复制代码
import requests

page = 0
content = ""
while True:
    url = f'https://push2ex.eastmoney.com/getTopicZTPool?ut=7eea3edcaed734bea9cbfc24409ed989&dpt=wz.ztzt&Pageindex={page}&pagesize=20&sort=fbt%3Aasc&date=20240923&_=1727104055700'
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"}
    res = requests.get(url, headers=headers)
    data = res.json()
    if len(data['data']['pool']) == 0:
        break
    for i in data['data']['pool']:
        # 代码
        code = i['c']
        # 名称
        n = i['n']
        # 涨跌幅
        zdp = i['zdp']
        zdp_float = str(round(zdp, 2)) + "%"
        # 最新价
        p = i['p']
        p_f = p / 1000
        p_number = round(p_f, 2)
        # 成交额
        amount = i['amount']
        str_amount = ""
        if amount >= 10 ** 8:
            amount /= 10 ** 8
            string = str(round(amount, 2)) + "亿"
            str_amount += string
        else:
            amount /= 10 ** 4
            string = str(round(amount)) + "万"
            str_amount += string
        # 流通市值
        ltsz = i['ltsz']
        str_ltsz = ""
        ltsz /= 10 ** 8
        str_ltsz += str(round(ltsz, 2)) + "亿"
        # 总价值
        tshare = i['tshare']
        str_tshare = ""
        tshare /= 10 ** 8
        str_tshare += str(round(tshare, 2)) + "亿"
        # 换手率
        hs = i['hs']
        str_hs = str(round(hs, 2)) + "%"
        # 封板资金
        fund = i['fund']
        str_fund = ""
        if fund >= 10 ** 8:
            fund /= 10 ** 8
            string = str(round(fund, 2)) + "亿"
            str_fund += string
        else:
            fund /= 10 ** 4
            string = str(round(fund, 1)) + "万"
            str_fund += string
        # 首次封板时间
        fbt = i['fbt']
        str_fbt = ""
        if fbt >= 100000:
            string = str(fbt)
            str_fbt += string[0:2] + ":" + string[2:4] + ":" + string[4:6]
        else:
            string = str(fbt)
            str_fbt += string[0:1] + ":" + string[1:3] + ":" + string[3:5]
        # 最后封板时间
        lbt = i['lbt']
        str_lbt = ""
        if lbt >= 100000:
            string = str(lbt)
            str_lbt += string[0:2] + ":" + string[2:4] + ":" + string[4:6]
        else:
            string = str(lbt)
            str_lbt += string[0:1] + ":" + string[1:3] + ":" + string[3:5]
        # 炸板次数
        zbc = i['zbc']
        str_zbc = str(zbc) + "次"
        # 涨停统计
        zttj = str(i['zttj']['ct']) + "/" + str(i['zttj']['days'])
        # 连版数
        lbc = i['lbc']
        str_lbc = ""
        if lbc == 1:
            string = "首版"
            str_lbc += string
        else:
            str_lbc = str(lbc) + "连扳"
        # 所属行业
        hybk = i['hybk']
        content += "代码:" + str(code) + ",名称:" + n + ",涨跌幅:" + str(zdp_float) + ",最新价(千):" + str(p_number) + ",成交额:" + str_amount + ",流通市值:" + str_ltsz + ",总价值:" + str_tshare + ",换手率:" + str_hs + ",封板资金:" + str_fund + ",首次封板时间:" + str_fbt + ",最后封板时间:" + str_lbt + ",炸板次数:" + str_zbc + ",涨停统计:" + zttj + ",连版数:" + str_lbc + ",所属行业:" + hybk + "\n"
        print("代码:", code, ",名称:", n, ",涨跌幅:", zdp_float, ",最新价(千):", p_number, ",成交额:", str_amount,
              ",流通市值:", str_ltsz, ",总价值:", str_tshare, ",换手率:", str_hs, ",封板资金:", str_fund,
              ",首次封板时间:", str_fbt, ",最后封板时间:", str_lbt, ",炸板次数:", str_zbc, ",涨停统计:", zttj,
              ",连版数:", str_lbc, ",所属行业:", hybk)
        # print(i)
    page += 1

with open("涨停股池.txt", "a", encoding="utf-8") as f:
    f.write(content)

这里面的代码, 将爬虫爬取到的数据先格式化了, 数据格式化的效果和网站上表格的数据是一样的, 然后再把爬虫爬取到的数据存入txt文件里面去()。

你写出来了吗?如果写出来的话, 给自己一个掌声哦。👏

以上就是爬虫请求响应以及提取数据的所有内容了, 如果有哪里不懂的地方,可以随时联系我, 我的qq号是1175235190, qq邮箱是1175235190@qq.com, 欢迎随时来提问题!!!
如果我有写错的地方, 望大家指正, 也可以联系我, 让我们一起努力, 继续不断的进步.
学习是个漫长的过程, 需要我们不断的去学习并掌握消化知识点, 有不懂或概念模糊不理解的情况下,一定要赶紧的解决问题, 否则问题只会越来越多, 漏洞也就越老越大.
人生路漫漫, 白鹭常相伴!!!

上一个
爬虫请求响应以及提取数据
下一个
爬虫post请求
最近修改: 2024-09-24Powered by