第一次爬的数据太少了,应老师要求要爬的数据不止三种,所以这次要进入详情页来抓取数据,跟上次的抓取格式有点不一样

稍微繁琐一些

不过爬51job相对于拉钩,boss直聘等招聘网站要轻松一些,反爬基本没遇到,,但是里边有一些“VIP”的网站,也就是说这些的网站跟其他网站构造有点不同,没办法用匹配其他网站的办法来对它们,然而我想的是直接就把这种网站先过滤出来在想办法专门对付他们。首先是先把详情页的url获取到页数可以自己改,我爬的是1000页:

from bs4 import BeautifulSoup
import requests
import csv
titles = []
f = open('E:/51JobData/job_url.csv', 'w', encoding='gbk', newline='')
f_csv = csv.writer(f)
f_csv.writerow(['URL'])
for i in range(1, 1000):
    try:
        url = 'https://search.51job/list/000000,000000,0000,00,9,99,%25E5%25A4%25A7%25E6%2595%25B0%25E6%258D%25AE,2,{}.html?lang=c&stype=&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=99&companysize=99&providesalary=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0&address=&line=&specialarea=00&from=&welfare='.format(str(i))
        response = requests.get(url)
        response.encoding = 'gbk'
        soup = BeautifulSoup(response.text)
        lists2 = soup.find_all('p', class_="t1")
        new_titles2 = [list_title.span.a['href'] for list_title in lists2] # 链接
        for i in new_titles2:
            f_csv.writerow([i])
    except Exception as e:
        print(e)
f.close()
print('抓取完毕!')

还有就是这里边的职位详情有点不好弄,我采用的方法是用beautifulsoup把这些元素所在的标签匹配出来然后用.text方法直接获取全部的职位信息

就例如上图这种,把<div class="bmsg job_msg inbox">这个标签匹配出来,之后再.text就获取了所有职位信息,但是也有一些不需要的信息,例如下图微信分享,职能类别,要把这些去掉,也简单,直接匹配出来<div class="mt10">和<div class="share">这俩标签中的text,再用总的减去这俩,但是有一些这种标签可能有时候会没有这里要判断一下

 

        # 职位信息
        ff = soup.find('div', class_="bmsg job_msg inbox")# 匹配到总的大标签
        if ff:
            chart = ff.find('div', class_="share")# 判断这个小标签是否存在
            if chart:# 如果存在
                information = str(ff.text).replace(str(ff.div.text), '').strip(str(chart)).replace('\xa0', '')# 大标签减去所有 div下的小text以及chart
                information = information.replace('\n', '').replace('\r', '')# 最后也要再去掉空格和换行
            else:
                information = 'information = str(ff.text).replace(str(ff.div.text), '').replace('\xa0', '')'# 如果chart不存在就不去掉它
                information = information.replace('\n', '').replace('\r', '')

薪资和职位名称以及福利都比较好匹配(找到标签位置dd = find('标签',class_=''),找到属性‘想要的数据 ’= dd.attrs['属性']):


            # 职位名称
            The_titleAnd_salary = soup.find('div', class_="cn")
            title = The_titleAnd_salary.h1.attrs['title']

            # 薪资
            salary = The_titleAnd_salary.strong.text
            The_all = soup.find('p', class_='msg ltype')             
            
            
            # 福利
            welfare = soup.find('div', class_="t1")  
            welfare = welfare.text.replace('\n', ',').replace('\r', '')

下一步就是['地点', '工作经验', '学历', '招聘人数', '发布时间'] 这几个关键词了,我也是直接.text提取的经过处理返回的是列表,但悲伤的是很多公司并不是全都五个,可是要写进csv,一个顺序错了,岂不是都错了,,,我选择了给那些不是五个的过滤掉单独处理,,,,不知道有没有小伙伴有好的办法呐,我这里把每一个匹配出来的信息都挨个加进去了,其中,company和title我是指定加入的位置,其他的都默认放在列表最后。

这样子最后出来一个完整的列表再写进去csv,一行一行地写,长度不大于五的标签我把它放进了列表里

            # 公司
            The_company = soup.find('a', class_="catn")
            company = The_company.attrs['title']
            all = The_all.text.strip().split('  |  ')
            if len(all) == 5:
                all[0:0] = [company, title]
                all.append(salary)
                all.append(information)
                all.append(welfare)
                all.append(url)
                csv_write.writerow(all)

            else:
              pool_url.append(url)

最后放出完整代码:

from bs4 import BeautifulSoup
import requests
import pandas as pd
import csv
import random
url = 'https://jobs.51job/kunshan/110730557.html?s=01&t=0'
f = open('E:/51JobData/JobCcountry1.csv', 'w', newline='', encoding='gbk')
csv_write = csv.writer(f)
csv_write.writerow(['公司', '职位名称', '地点', '工作经验', '学历', '招聘人数', '发布时间', '薪资', '职位信息', '福利', 'url'])
df = pd.read_csv('E:/51JobData/job_url.csv', engine='python', encoding='gbk', header=0)
pool_url = []

header_list = [
    #火狐
    {"user-agent" : "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"},
    #谷歌
    {"user-agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11"},
    # IE
    {"user-agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763"}
]
header = random.choice(header_list)
for i, row in df.iterrows():
    try:
        url = row['URL']
        response = requests.get(url, headers = header)
        response.encoding = 'gbk'
        soup = BeautifulSoup(response.text)

        # 福利
        welfare = soup.find('div', class_="t1")  # 福利
        welfare = welfare.text.replace('\n', ',').replace('\r', '')

        # 职位信息
        ff = soup.find('div', class_="bmsg job_msg inbox")
        if ff:
            chart = ff.find('div', class_="share")
            if chart:
                information = str(ff.text).replace(str(ff.div.text), '').strip(str(chart)).replace('\xa0', '')
                information = information.replace('\n', '').replace('\r', '')
            else:
                information = ''


            # 职位名称
            The_titleAnd_salary = soup.find('div', class_="cn")
            title = The_titleAnd_salary.h1.attrs['title']

            # 薪资
            salary = The_titleAnd_salary.strong.text
            The_all = soup.find('p', class_='msg ltype')

            # 公司
            The_company = soup.find('a', class_="catn")
            company = The_company.attrs['title']
            all = The_all.text.strip().split('  |  ')
            if len(all) == 5:
                all[0:0] = [company, title]
                all.append(salary)
                all.append(information)
                all.append(welfare)
                all.append(url)
                csv_write.writerow(all)

            else:
              pool_url.append(url)
        print('第{}条数据'.format(str(i)))
    except Exception as e:
        pool_url.append(url)
        print(e)
    df = pd.DataFrame(pool_url)
    df.to_csv('E:/51JobData/JobSpecial.csv',  encoding='gbk', index=False, header=0)
print('爬取完毕!')

 

我用这个代码爬了大约三万条,但其中一万条被过滤掉了(悲伤至极)我回头还要再处理那部分数据,处理完成要对数据进行清洗与分析,博文持续更新中...........

欢迎纠错

更多推荐

轻松爬51job(二)