按F12打开开发者工具抓包,可以定位到招聘信息的接口

python使用requests库爬取拉勾网招聘信息的实现

在请求中可以获取到接口的url和formdata,表单中pn为请求的页数,kd为关请求职位的关键字

python使用requests库爬取拉勾网招聘信息的实现

python使用requests库爬取拉勾网招聘信息的实现

使用python构建post请求

data = {
  'first': 'true',
  'pn': '1',
  'kd': 'python'
}

headers = {
  'referer': 'https://www.lagou.com/jobs/list_python/p-city_0"https://www.lagou.com/jobs/positionAjax.json", data=data,headers=headers)
print(res.text)

发现没有从接口获取到数据

python使用requests库爬取拉勾网招聘信息的实现

换了个网络后接口还是会返回操作频繁的错误信息,仔细检查后发现这个接口需要一个动态的cookies不然会一值返回错误频繁

data = {
  'first': 'true',
  'pn': '1',
  'kd': 'python'
}

#头部中必须有user-agent和referer不然不会返回cookies
headers = {
  'referer': 'https://www.lagou.com/jobs/list_python/p-city_0"https://www.lagou.com/jobs/list_python/p-city_0",headers=headers)

#再post请求中传入cookies
r2 = requests.post("https://www.lagou.com/jobs/positionAjax.json", data=data,headers=headers, cookies=r2.cookies)
print(r2.text)

注意!每请求十次接口cookies也会刷新一次,下面贴上完整爬虫代码

import json
import logging

import requests

#获取cookie
def getCookie():
  res = requests.get("https://www.lagou.com/jobs/list_python/p-city_0",
        headers=headers)
  return res.cookies

#获取json数据
def getPage(i, cookies, kw):
  data = {
    'first': 'true',
    'pn': i,
    'kd': kw
  }
  res = requests.post("https://www.lagou.com/jobs/positionAjax.json", data=data,
             headers=headers, cookies=cookies)
  return json.loads(res.text)

#合并列表
def reduceList(l):
  text = ""
  for i in l:
    text += i + " "
  return text.strip()

#提取字段并保存到文件中
def saveInCsv(f, data):
  js = data["content"]["positionResult"]["result"]
  for node in js:

    # 对空值进行处理
    district = node["district"]
    if district != None:
      district = "-" + district
    else:
      district = ""

    f.write(
      node["positionName"] + "·" + node["city"] + district + "·" + node[
        "salary"] + "·" +
      node["workYear"] + "·" + node["education"] + "·" + reduceList(node["skillLables"]) + "·" +
      node["companyShortName"] + "·" + node["companySize"] + "·" + node["positionAdvantage"] + "\n")

if __name__ == '__main__':
  #定义头部
  headers = {
    'referer': 'https://www.lagou.com/jobs/list_python/p-city_0"file.csv", "w", encoding="utf-8") as f:
    for i in range(1, 31):
      #每十个请求重新获取cookie
      if (i % 10 == 0):
        cookies = getCookie()

      #解析字段并存储
      data = getPage(i, cookies, "python")
      saveInCsv(f, data)
标签:
python,requests爬取拉勾网,python,requests爬取

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。