根据搜索内容爬取拉钩网和招聘网的职位招聘信息

代码:

import requests
import time
import random

ip_list = ['117.135.132.107', '121.8.98.196',  '194.116.198.212']

#http请求头信息
headers={
'Accept':'application/json, text/javascript, */*; q=0.01',
'Accept-Encoding':'gzip, deflate, br',
'Accept-Language':'zh-CN,zh;q=0.8',
'Connection':'keep-alive',
'Content-Length':'25',
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
'Cookie':'user_trace_token=20170214020222-9151732d-f216-11e6-acb5-525400f775ce; LGUID=20170214020222-91517b06-f216-11e6-acb5-525400f775ce; JSESSIONID=ABAAABAAAGFABEF53B117A40684BFB6190FCDFF136B2AE8; _putrc=ECA3D429446342E9; login=true; unick=yz; showExpriedIndex=1; showExpriedCompanyHome=1; showExpriedMyPublish=1; hasDeliver=0; PRE_UTM=; PRE_HOST=; PRE_SITE=; PRE_LAND=https%3A%2F%2Fwww.lagou.com%2F; TG-TRACK-CODE=index_navigation; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1494688520,1494690499,1496044502,1496048593; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1496061497; _gid=GA1.2.2090691601.1496061497; _gat=1; _ga=GA1.2.1759377285.1487008943; LGSID=20170529203716-8c254049-446b-11e7-947e-5254005c3644; LGRID=20170529203828-b6fc4c8e-446b-11e7-ba7f-525400f775ce; SEARCH_ID=13c3482b5ddc4bb7bfda721bbe6d71c7; index_location_city=%E6%9D%AD%E5%B7%9E',
'Host':'www.lagou.com',
'Origin':'https://www.lagou.com',
'Referer':'https://www.lagou.com/jobs/list_Python?',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
'X-Anit-Forge-Code':'0',
'X-Anit-Forge-Token':'None',
'X-Requested-With':'XMLHttpRequest'
}

def get_json(url,page,lange_name):
    #构造一个framdata数据
    FramData = {'firts':'true','pn':page,'kd':lange_name}
    #采用request是post方法,返回requests<200>,访问成功
    JsonDatas = requests.post(url,FramData,headers=headers,proxies={'http': 'http://' + random.choice(ip_list)}).json()
    #获取字典数据
    #JsonDatas = jsonData.json()
    return  JsonDatas

def parser_json(page,JsonDatas):#JsonDatas数据库类型是字典
    #total = int(JsonDatas['content']['positionResult']['totalCount'])
    companyInfos = []
    #获取招聘信息的公司,列表类型
    companyInfo = JsonDatas['content']['positionResult']['result']
    #对每一个公司遍历
    print("正在解析{0}页招聘信息".format(page))
    for company in companyInfo:
        #定义一个列表,暂时存储一个公司信息
        comInfo = []
        #公司所在城市
        if company['district'] is not None:
            city =  company['city'] + '-' + company['district']
        else:
            city = company['city']
        #print(city)
        comInfo.append(city)
        # 职位名称
        positionName = company['positionName']
        #print(positionName)
        comInfo.append(positionName)
        #获取公司名称
        companyFullName = company['companyFullName']+ '(' + company['companyShortName'] + ')'
        #print(companyFullName)
        comInfo.append(companyFullName)
        #要求学历
        education = company['education']
        #print(education)
        comInfo.append(education)
        #职位类型
        jobNature = company['jobNature']
        #print(jobNature)
        comInfo.append(jobNature)
        #职位待遇
        positionAdvantages = company['positionAdvantage']
        positionAdvantage = positionAdvantages.replace(',',';').replace(',',';')
        #print(positionAdvantage)
        comInfo.append(positionAdvantage)
        #工资
        salary = company['salary']
        #print(salary)
        comInfo.append(salary)
        #经验要求
        workYear = company['workYear']
        comInfo.append(workYear)
        #分布时间
        time = company['createTime']
        comInfo.append(time)
        #将每个公司的信息加入companyInfos中
        companyInfos.append(comInfo)
    print("第{0}页解析完成".format(page))
    return companyInfos
def writeCSV(page,fw,companyInfos):
    for companyInfo in companyInfos:
        #print(companyInfo)
        fw.write(",".join(companyInfo)+'\n')
    print("第{0}页数据写入完毕".format(page))
    
def main():
    path = 'F:'  # 文件存储路径
    start_page = 1
    end_page = 20 #默认
    lange_name = input("请输入要所有的职位:")
    city = input("请输入工作地点:")
    #创建文件
    fw = open(path + '\lagou_' + lange_name + '.csv', 'a+')
    #构造url链接
    start_url = 'https://www.lagou.com/jobs/positionAjax.json?px=default&city='
    end_url = '&needAddtionalResult=false&isSchoolJob=0'
    url=start_url + city + end_url
    page = start_page
    row = ['工作地点','职位名称', '公司名称', '要求学历', '工作性质', '工作福利', '薪水', '工作经验要求','发布时间']
    fw.write(",".join(row) + '\n')
    while page < end_page:
        time.sleep(12)
        print("正在抓取第{0}页招聘数据信息".format(page))
        #获取json数据
        JsonDatas = get_json(url,page,lange_name)
        #对获取的数据进行解析
        companyInfos = parser_json(page,JsonDatas)
        #将信息写入CSV文件中
        writeCSV(page,fw,companyInfos)
        page = page+1
    print("所有数据写入完毕")

if __name__ == '__main__':
    main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是 scrapy 爬取拉钩的步骤: 1. 创建 scrapy 项目 在命令行中输入以下命令来创建 Scrapy 项目: ``` scrapy startproject lagou ``` 其中,`lagou` 是项目名称。 2. 创建爬虫 在项目的根目录下,使用以下命令创建一个爬虫: ``` scrapy genspider lagou_spider www.lagou.com ``` 其中,`lagou_spider` 是爬虫名称,`www.lagou.com` 是要爬取站的域名。 3. 编写爬虫代码 打开 `lagou_spider.py` 文件,将其修改为以下内容: ```python import scrapy class LagouSpider(scrapy.Spider): name = "lagou" allowed_domains = ["www.lagou.com"] start_urls = ["https://www.lagou.com/"] def parse(self, response): pass ``` 我们定义了一个 `LagouSpider` 类,并指定了名称、域名和起始 URL。在 `parse` 方法中,我们暂时没有写任何代码,因为我们需要先分析站的页面结构和数据格式,才能编写爬虫代码。 4. 分析页面结构和数据格式 使用浏览器打开拉钩站,进入搜索职位界面,选择一个职位类型,例如 Python 开发,然后按下搜索按钮。此时,浏览器会跳转到一个新的页面,该页面的 URL 会包含搜索的关键词。例如,搜索 Python 开发,URL 为 `https://www.lagou.com/zhaopin/Python/`。 我们打开浏览器的开发者工具,切换到 Network 选项卡,然后点击搜索按钮。此时,我们会看到浏览器发送了多个请求,其中一个是 `https://www.lagou.com/jobs/positionAjax.json`,该请求返回搜索结果的 JSON 数据。我们可以点击该请求,然后在 Preview 选项卡中查看数据格式。 我们可以看到,返回JSON 数据包含了多个职位的信息,每个职位包含了如下字段: - `companyFullName` 公司全名 - `companyShortName` 公司简称 - `companySize` 公司规模 - `district` 工作地点 - `education` 学历要求 - `financeStage` 融资阶段 - `firstType` 职位类别 - `industryField` 行业领域 - `positionAdvantage` 职位诱惑 - `positionId` 职位ID - `positionName` 职位名称 - `salary` 薪资范围 - `secondType` 职位子类别 - `workYear` 工作经验 现在,我们已经了解了数据的格式,可以开始编写爬虫代码了。 5. 完善爬虫代码 我们需要在 `parse` 方法中,向 `https://www.lagou.com/jobs/positionAjax.json` 发送请求,获取 JSON 数据,并解析数据,提取职位信息。 以下是完整的爬虫代码: ```python import scrapy import json class LagouSpider(scrapy.Spider): name = "lagou" allowed_domains = ["www.lagou.com"] start_urls = ["https://www.lagou.com/"] def parse(self, response): job_types = ["Python", "Java", "PHP", "C++", "C#", "Ruby", "Scala", "Go", "Swift"] for job_type in job_types: url = "https://www.lagou.com/jobs/positionAjax.json?px=default&city=%E5%8C%97%E4%BA%AC&needAddtionalResult=false&isSchoolJob=0" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.2236.0 Safari/537.36 Edg/114.0.2236.0", "Referer": f"https://www.lagou.com/zhaopin/{job_type}/" } data = { "first": "false", "pn": "1", "kd": job_type } yield scrapy.Request(url=url, method="POST", headers=headers, body=json.dumps(data), callback=self.parse_job_list, meta={"job_type": job_type}) def parse_job_list(self, response): job_type = response.meta["job_type"] result = json.loads(response.text) for job in result["content"]["positionResult"]["result"]: yield { "job_type": job_type, "position_name": job["positionName"], "salary": job["salary"], "company_full_name": job["companyFullName"], "work_year": job["workYear"], "education": job["education"], "job_nature": job["jobNature"], "position_advantage": job["positionAdvantage"] } ``` 在 `parse` 方法中,我们通过循环遍历多个职位类型,向 `https://www.lagou.com/jobs/positionAjax.json` 发送 POST 请求,获取 JSON 数据。我们在请求头中设置了 User-Agent 和 Referer,以便绕过反爬虫机制。我们在请求体中设置了查询参数,其中 `kd` 表示搜索职位类型。我们使用 `json.dumps` 方法将请求体转换为 JSON 格式,并将结果作为请求体发送。 在 `parse_job_list` 方法中,我们解析返回JSON 数据,并提取了职位信息。我们使用 `yield` 关键字将每个职位信息生成为一个字典,然后交给 Scrapy 引擎处理。 6. 运行爬虫 在命令行中进入项目的根目录,然后输入以下命令,运行爬虫: ``` scrapy crawl lagou -o lagou.json ``` 其中,`-o lagou.json` 表示将爬取数据保存到 `lagou.json` 文件中。您可以根据需要修改文件名和路径。 7. 结果分析 打开生成的 `lagou.json` 文件,您可以看到爬取到的数据。每个职位信息都包含了职位类型、职位名称、薪资范围、公司全名、工作经验、学历要求、职位性质和职位诱惑等字段。您可以根据需要对数据进行分析和处理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值