python爬取boss直聘某职位信息(selenium+chrome的应用)

本文介绍使用Selenium爬取Boss直聘网站特定职位信息的方法,包括登录、数据抓取及CSV存储过程,解决模拟浏览器登录及多页面爬取难题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要是记录一下借助selenium实现数据获取。以boss直聘为目标网站,主要目的是爬取指定职位的相关信息,以csv形式存在了本地。

主要思路
  1. 利用selenium打开模拟浏览器,访问boss直聘url:https://www.zhipin.com/
  2. 输入某职位,点击搜索
  3. 在搜索结果页面,解析出现的职位信息,并保存
  4. 存在多个页面时,跳转至下一页。重复步骤3
需注意的点

用模拟浏览器打开时,搜索某职位后,页面会跳至注册页面,需要登录后才能查看信息,这里事先存入cookies,打开首页,利用browser.add_cookie()附上事前存好的cookies,页面刷新后再执行步骤2。
cookies保存的方法:
我这里是用selenium打开登录页面后,手动登录,然后保存当前的cookies至本地

from selenium import webdriver
import json
 
browser = webdriver.Chrome()
browser.get('https://login.zhipin.com/?ka=header-login')
# 在弹出的模拟浏览器上手动登录
cookies = browser.get_cookies()
with open('boss_cookies.json', 'w', encoding='utf-8') as f:
    f.write(json.dumps(cookies))
待解决的问题

想直接利用selenium进行登录,但是在登录页面无法拖拽验证,看了好多资料也没解决·····欢迎留言解决方案,万分感谢~~~
已经尝试过的解决方案:
隐藏自己是模拟浏览器 ,详细可参考:一行js代码识别Selenium+Webdriver及其应对方案

from selenium.webdriver import Chrome from selenium.webdriver import ChromeOptions

option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation']) driver = Chrome(options=option)

我在找答案的过程中,开始发现连手动拖拽都会报错,后来发现是Chrome和ChromeDriver版本不相符造成的,后续安装还是升级版本时,一定要记得Chrome和ChromeDriver版本要一致。 后来更新了版本后,至少手动拖拽是成功了的 ······

整体代码
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver import ChromeOptions
import json, csv
import time
import random

def inquire_job(browser, job_name):
    # 输入需要查询的职位
    input_string = browser.find_element_by_css_selector('.ipt-search')
    input_string.send_keys(job_name)

    button = browser.find_element_by_class_name('btn')
    button.click()


def get_job_items(browser):
    # 解析当前页面职位
    items = browser.find_elements_by_xpath("//div[@class='job-list']//li")

    file = open('boss_job_items.csv', 'a', encoding='utf-8')
    fieldnames = ['job_title', 'job_url', 'salary', 'condition', 'company_title', 'company_url',
                 'company_info', 'publis_name']
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    for item in items:
        result = {}
        job = item.find_element_by_class_name('info-primary')
        result['job_title'] = job.find_element_by_class_name('job-title').text
        result['job_url'] = job.find_element_by_css_selector('a').get_attribute('href')
        result['salary'] = job.find_element_by_class_name('red').text
        result['condition'] = job.find_element_by_css_selector('p').text
        # '杭州 下城区 朝晖1-3年大专'
        company = item.find_element_by_class_name('info-company')
        result['company_title'] = company.find_element_by_css_selector('a').text
        result['company_url'] = company.find_element_by_css_selector('a').get_attribute('href')
        result['company_info'] = company.find_element_by_css_selector('p').text

        publis = item.find_element_by_class_name('info-publis')
        result['publis_name'] = publis.find_element_by_class_name('name').text

        writer.writerow(result)

    file.close()


def get_next_page(browser):
    # 翻页操作
    try:
        pages = browser.find_element_by_class_name('page')
        next_page_url = pages.find_element_by_class_name('next').get_attribute('href')
        print(next_page_url)
        return next_page_url
    except NoSuchElementException:
        raise NoSuchElementException


def main(job_name):
    # 避免被识别出为模拟浏览器
    options = ChromeOptions()
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    options.add_argument('--headless')
    browser = webdriver.Chrome(options=options)
    
	# 获取本地cookies
    with open('boss_cookies.json', 'r') as file:
        data = file.read()
        cookies = json.loads(data)
	# 加载cookies后刷新页面
    browser.get('https://www.zhipin.com/')
    for i in cookies:
        browser.add_cookie(i)
    browser.refresh()

    while True:
        try:
            inquire_job(browser, job_name)
            time.sleep(1)
            get_job_items(browser)
            next_page_url = get_next_page(browser)
            time.sleep(random.uniform(1, 10))
            browser.get(next_page_url)
        except Exception:
            break

    browser.close()


if __name__ == '__main__':
    start_time = time.time()
    main('python爬虫')
    end_time = time.time()
    print(end_time - start_time)

### 数据爬取方案 为了实现从 Boss 网站上爬取大数据相关招信息的目标,可以基于 Selenium 和 Beautiful Soup 的组合完成这一任务。以下是具体的实现方法: #### 使用 Selenium 进行网页交互 由于 Boss 可能涉及动态加载内容以及反爬机制,因此推荐使用 Selenium 来模拟真实用户的浏览器行为。这一步骤主要用于登录、翻页和提取页面中的 HTML 内容。 ```python from selenium import webdriver import time # 初始化 WebDriver (需提前下载对应版本的 ChromeDriver 或其他驱动程序) driver = webdriver.Chrome() try: driver.get("https://www.zhipin.com/") # 打开目标网址 time.sleep(3) # 等待页面加载 # 输入关键词“大数据” search_box = driver.find_element_by_css_selector("#keyword") # 定位搜索框 search_box.send_keys("大数据") # 提交表单 submit_button = driver.find_element_by_css_selector(".search-btn") submit_button.click() # 获取当前页面源码 page_source = driver.page_source finally: driver.quit() # 关闭浏览器实例 ``` 此部分代码实现了打开 Boss 首页、输入关键字“大数据”并提交搜索的功能[^1]。 --- #### 利用 Beautiful Soup 解析数据 在获取到页面的 HTML 源码之后,可以通过 Beautiful Soup 对其进行解析,从而提取所需的字段信息(如职位名称、薪资范围、工作地点等)。 ```python from bs4 import BeautifulSoup soup = BeautifulSoup(page_source, 'html.parser') job_listings = soup.select('.job-primary') # 查找所有职位列表项 data = [] for job in job_listings: title = job.select_one('div.info-primary h3.name').text.strip() # 职位名 salary = job.select_one('span.red').text.strip() # 薪资 company_name = job.select_one('div.company-text a').text.strip() # 公司名 location = job.select_one('p.info-primary span').text.strip() # 工作地点 data.append({ "title": title, "salary": salary, "company_name": company_name, "location": location }) ``` 上述代码片段展示了如何通过 CSS 选择器定位各个字段,并将其存储为结构化的字典形式[^2]。 --- #### 数据保存与后续分析 最后,可借助 pandas 将收集的数据导出至 CSV 文件以便进一步处理;同时还可以调用 matplotlib 或 pyecharts 实现可视化展示。 ```python import pandas as pd df = pd.DataFrame(data) df.to_csv("big_data_jobs.csv", index=False) print("数据已成功保存!") ``` 至此完成了整个流程的设计——从初始访问至最终结果输出。 ---
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值