2021-05-30-爬取51job-数据分析

爬取51job-数据分析

import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from bs4 import BeautifulSoup
import csv

def page_generator():
    web = webdriver.Chrome()
    web.maximize_window()
    try:
        web.get('https://www.51job.com/')

        input = web.find_element_by_id('kwdselectid')
        input.send_keys('数据分析')
        input.send_keys(Keys.ENTER)

        while True:
            location = web.find_element_by_css_selector('div.clist > a:nth-child(1)')
            if location.text == '全国':
                break
            location.click()
            time.sleep(1)

        old_url = web.current_url
        max_try = 5
        try_count = 0
        while True:
            print(web.current_url)
            # max_height = 600
            # height = 100
            # while True:
            #     web.execute_script(f'window.scrollTo(0, {height})')
            #     height += 100
            #     if height > max_height:
            #         break
            # yield web.execute_script('return window.__SEARCH_RESULT__["engine_search_result"]')
            text = web.page_source
            try:
                # 网络以及翻页速度等原因造成部分页面加载不全的情况,如果下一页标签没出现,则报异常
                next_btn = web.find_element_by_css_selector('li.next')
                next_btn.click()
            except selenium.common.exceptions.ElementNotInteractableException as e:
                # 异常时,最多执行5次重新获取,5次都获取不到可能网页元素有变,这时,不在反复执行
                print('page_url:', web.current_url, '\terror:', e)
                try_count += 1
                if try_count < max_try:
                    # 取不到页面时,停顿一定时间后在尝试,否则时间太短,相同的问题会一直触发
                    time.sleep(1)
                    continue
                else:
                    break
            # 使用生成器获取页面
            yield text
            time.sleep(0.1)
            # 最后一页跳下一页,因为下一页不存在,所以地址和最后一页相同,因此当前页为最后一页的时候跳出
            if old_url == web.current_url:
                break
            old_url = web.current_url
            try_count = 0
    finally:
        web.close()

def analysis_data(content: str):
    res = []
    soup = BeautifulSoup(content, 'lxml')
    boxs = soup.select('div.j_joblist > div')
    for box in boxs:
        job_href = box.select_one('a').attrs['href']
        job_name = box.select_one('a > p.t > span.jname.at').get_text()
        updatedate = box.select_one('a > p.t > span.time').get_text()
        tags = box.select_one('a > p.t > em')
        tags = tags.attrs['alt'] if tags else ''
        # 包含工作地点和条件
        workplace_attribute = box.select_one('a > p.info > span.d.at').get_text()
        salary = box.select_one('a > p.info > span.sal').get_text()
        company_name = box.select_one('div.er > a').get_text()
        company_href = box.select_one('div.er > a').attrs['href']
        # 公司类型以及公司人数规模
        companytype = box.select_one('div.er > p.dc.at').get_text().strip()
        companyind = box.select_one('div.er > p.int.at').get_text()
        jobwelf = box.select_one('a > p.tags')
        jobwelf = jobwelf.attrs['title'] if jobwelf else ''
        res.append([job_name, job_href, updatedate, tags, workplace_attribute, salary, company_name, company_href, companytype, companyind, jobwelf])
        # print(job_name, job_href, updatedate, tags, workplace_attribute, salary, company_name, company_href, companytype, companyind, jobwelf)
    return res


if __name__ == '__main__':
    page = page_generator()
    with open(r'./csvfile/51job.csv', 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(['job_name', 'job_href', 'updatedate', 'tags', 'workplace_attribute', 'salary', 'company_name', 'company_href', 'companytype', 'companyind', 'jobwelf'])

    with open(r'./csvfile/s51job.csv', 'a', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        try:
            while True:
                date = next(page)
                res = analysis_data(date)
                writer.writerows(res)
        except StopIteration:
            print('页面加载完毕...')
        finally:
            print('程序运行结束...')
    # print('='*40)
    # print(next(page))
    # with open(r'./temp.html', 'w', encoding='utf-8') as f:
    #     f.write(next(page))
    #
    # with open(r'./temp.html', 'r', encoding='utf-8') as f:
    #     html = f.read()
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
为了从51job网站上爬取和清洗Python相关的数据,可以按照以下步骤进行操作: 1. 使用Python的requests模块发送HTTP请求,获取51job网站上的页面内容。可以使用如下代码片段作为示例: ```python import requests url = "https://search.51job.com/list/170200,000000,0000,00,9,99,python,2,1.html?lang=c&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=99&companysize=99&ord_field=0&dibiaoid=0&line=&welfare=" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0" } response = requests.get(url, headers=headers) ``` 2. 使用Python的HTML解析库,例如BeautifulSoup,解析网页内容并提取所需的数据。根据你的需求,你可以提取职位标题、发布日期、工资、工作地点、工作经验、学历要求、招聘人数、公司类别和公司规模等信息。 3. 将提取的数据保存到本地文件,例如CSV文件。你可以使用Python的CSV模块将数据写入CSV文件中,以便后续的数据清洗和分析。 4. 对保存的数据进行清洗和处理。根据你的需求,可能需要删除重复的数据、处理缺失值、格式化日期等。 5. 使用可视化库,例如pyecharts,对清洗后的数据进行可视化展示。你可以根据数据的特点选择适当的图表类型,如柱状图、折线图等,以帮助你更好地理解和分析数据。 通过以上步骤,你可以使用Python爬取和清洗51job网站上的Python相关数据,并对数据进行可视化展示。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [记一次虫学习(爬取51job)](https://blog.csdn.net/qq_52720527/article/details/124368257)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值