源代码:https://github.com/nnngu/LagouSpider


效果预览

思路

1、首先我们打开拉勾网,并搜索“java”,显示出来的职位信息就是我们的目标。

2、接下来我们需要确定,怎样将信息提取出来。

  • 查看网页源代码,这时候发现,网页源代码里面找不到职位相关信息,这证明拉勾网关于职位的信息是异步加载的,这也是一种很常用的技术。

  • 异步加载的信息,我们需要借助 chrome 浏览器的开发者工具进行分析,打开开发者工具的方法如下:

  • 点击Nerwork进入网络分析界面,这时候是一片空白,刷新一下界面就可以看到一系列的网络请求了。

  • 前面我们说到,拉勾网关于职位的信息是异步加载的,那么在这一系列的网络请求中,必定有某个请求发送给服务器,响应回来的是职位信息。

  • 正常情况下,我们可以忽略css,图片等类型的请求,关注点放在XHR这种类型请求上,如图:

一共4个XHR类型的请求,我们逐个打开对比,分别点击Preview就能看到它们响应的内容。

发现第一个请求就是我们要找的。如图:

点击Headers,查看一下请求参数。如下图:

到此,我们可以确定city参数就是城市,pn参数就是页数,kd参数就是搜索关键字。

接下来开始写代码了。

代码

代码分成四个部分,便于后期维护。

1、基本 https 请求https.py

这部分对 requests 包进行了一些封装,部分代码如下:

# -*- coding: utf-8 -*-
from src.setting import IP, UA
import requests, random
import logging class Http:
'''
http请求相关的操作
''' def __init__(self):
pass def get(self, url, headers=None, cookies=None, proxy=None, timeOut=5, timeOutRetry=5):
'''
获取网页源码
url: 网页链接
headers: headers
cookies: cookies
proxy: 代理
timeOut: 请求超时时间
timeOutRetry: 超时重试次数
return: 源码
'''
if not url:
logging.error('GetError url not exit')
return 'None' # 这里只展示了一部分代码
# 完整代码已上传到Github

这里只展示了一部分代码,完整代码已上传到Github

2、代码主逻辑部分main.py

这部分的程序逻辑,如下:

  • 获取职位信息
def getInfo(url, para):
"""
获取信息
"""
generalHttp = Http()
htmlCode = generalHttp.post(url, para=para, headers=headers, cookies=cookies)
generalParse = Parse(htmlCode)
pageCount = generalParse.parsePage()
info = []
for i in range(1, 3):
print('第%s页' % i)
para['pn'] = str(i)
htmlCode = generalHttp.post(url, para=para, headers=headers, cookies=cookies)
generalParse = Parse(htmlCode)
info = info + getInfoDetail(generalParse)
time.sleep(2)
return info
  • 对信息进行储存
def processInfo(info, para):
"""
信息存储
"""
logging.error('Process start')
try:
title = '公司名称\t公司类型\t融资阶段\t标签\t公司规模\t公司所在地\t职位类型\t学历要求\t福利\t薪资\t工作经验\n'
file = codecs.open('%s职位.xls' % para['city'], 'w', 'utf-8')
file.write(title)
for p in info:
line = str(p['companyName']) + '\t' + str(p['companyType']) + '\t' + str(p['companyStage']) + '\t' + \
str(p['companyLabel']) + '\t' + str(p['companySize']) + '\t' + str(p['companyDistrict']) + '\t' + \
str(p['positionType']) + '\t' + str(p['positionEducation']) + '\t' + str(
p['positionAdvantage']) + '\t' + \
str(p['positionSalary']) + '\t' + str(p['positionWorkYear']) + '\n'
file.write(line)
file.close()
return True
except Exception as e:
print(e)
return None

3、信息解析部分parse.py

这部分针对服务器返回的职位信息的特点,进行解析,如下:

class Parse:
'''
解析网页信息
''' def __init__(self, htmlCode):
self.htmlCode = htmlCode
self.json = demjson.decode(htmlCode)
pass def parseTool(self, content):
'''
清除html标签
'''
if type(content) != str: return content
sublist = ['<p.*?>', '</p.*?>', '<b.*?>', '</b.*?>', '<div.*?>', '</div.*?>',
'</br>', '<br />', '<ul>', '</ul>', '<li>', '</li>', '<strong>',
'</strong>', '<table.*?>', '<tr.*?>', '</tr>', '<td.*?>', '</td>',
'\r', '\n', '&.*?;', '&', '#.*?;', '<em>', '</em>']
try:
for substring in [re.compile(string, re.S) for string in sublist]:
content = re.sub(substring, "", content).strip()
except:
raise Exception('Error ' + str(substring.pattern))
return content # 这里只展示了一部分代码
# 完整代码已上传到Github

这里只展示了一部分代码,完整代码已上传到Github

4、配置部分setting.py

这部分加入 cookies 的原因是为了应对拉勾网的反爬,长期使用需要进行改进,进行动态 cookies 获取

# -*- coding: utf-8 -*-

# headers
headers = {
'Host': 'www.lagou.com',
'Connection': 'keep-alive',
'Content-Length': '23',
'Origin': 'https://www.lagou.com',
'X-Anit-Forge-Code': '0',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'X-Requested-With': 'XMLHttpRequest',
'X-Anit-Forge-Token': 'None',
'Referer': 'https://www.lagou.com/jobs/list_java?city=%E5%B9%BF%E5%B7%9E&cl=false&fromSearch=true&labelWords=&suginput=',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7'
}

测试

运行结果:

爬取结束后,在src目录下就可以看到爬虫爬取到的数据。

到此,拉勾网的职位信息抓取就完成了。完整代码已经上传到我的Github

通俗易懂的分析如何用Python实现一只小爬虫,爬取拉勾网的职位信息的更多相关文章

  1. python爬虫--爬取某网站电影信息并写入mysql数据库

    书接上文,前文最后提到将爬取的电影信息写入数据库,以方便查看,今天就具体实现. 首先还是上代码: # -*- coding:utf-8 -*- import requests import re im ...

  2. python 小爬虫爬取博客文章初体验

    最近学习 python 走火入魔,趁着热情继续初级体验一下下爬虫,以前用 java也写过,这里还是最初级的爬取html,都没有用html解析器,正则等...而且一直在循环效率肯定### 很低下 imp ...

  3. Python 2.7_利用xpath语法爬取豆瓣图书top250信息_20170129

    大年初二,忙完家里一些事,顺带有人交流爬取豆瓣图书top250 1.构造urls列表 urls=['https://book.douban.com/top250?start={}'.format(st ...

  4. python爬虫实战之爬取智联职位信息和博客文章信息

    1.python爬取招聘信息 简单爬取智联招聘职位信息 # !/usr/bin/env python # -*-coding:utf-8-*- """ @Author  ...

  5. python爬虫爬取腾讯招聘信息 (静态爬虫)

    环境: windows7,python3.4 代码:(亲测可正常执行) import requests from bs4 import BeautifulSoup from math import c ...

  6. python简单小爬虫爬取易车网图片

    上代码: import requests,urllib.request from bs4 import BeautifulSoup url = 'http://photo.bitauto.com/' ...

  7. python爬虫爬取ip记录网站信息并存入数据库

    import requests import re import pymysql #10页 仔细观察路由 db = pymysql.connect("localhost",&quo ...

  8. python爬取拉勾网数据并进行数据可视化

    爬取拉勾网关于python职位相关的数据信息,并将爬取的数据已csv各式存入文件,然后对csv文件相关字段的数据进行清洗,并对数据可视化展示,包括柱状图展示.直方图展示.词云展示等并根据可视化的数据做 ...

  9. 爬取拉勾网python工程师的岗位信息并生成csv文件

    转载自:https://www.cnblogs.com/sui776265233/p/11146969.html 代码写得很好,但是目前只看得懂前一部分 一.爬取和分析相关依赖包 Python版本: ...

随机推荐

  1. 记录CentOS环境下将Solr部署到Tomcat

    首先切换到usr/local目录 cd /usr/local/ 下载tomcat到local目录 wget http://archive.apache.org/dist/tomcat/tomcat-7 ...

  2. Echars 6大公共组件详解

    Echars 六大组件详解 : title  tooltip toolbox legend  dataZoom visualMap 一.title标题详解 myTitleStyle = { color ...

  3. equals和hashcode重写的问题

    public static void main(String[] args) { Set<Test> set = new HashSet<>(); Test t1 = new ...

  4. React Native分享第三方遇到的问题

    这几天做APP的分享,好多东西都不懂,踩了好多坑,所幸现在做好了,开心^_^ 时间紧,随便记一下先. 1.签名文件要和各平台的签名一致 2.新浪微博和微信的分享要打包之后,加上签名了才可以(我一直不知 ...

  5. vue 购物车练习

    本人看了vue官网上的教程后,感觉对vue的依稀有点了解,决定动手练习个小功能项目,就找了购物车本项目.原文链接:http://blog.csdn.net/take_dream_as_horse/ar ...

  6. 【ASP.NET Core分布式项目实战】(三)整理IdentityServer4 MVC授权、Consent功能实现

    本博客根据http://video.jessetalk.cn/my/course/5视频整理(内容可能会有部分,推荐看源视频学习) 前言 由于之前的博客都是基于其他的博客进行开发,现在重新整理一下方便 ...

  7. Fiddler抓取https证书问题

    正常的使用方法  Fiddler 抓包工具总结    大部分问题的解决方案  fiddler4在win7抓取https的配置整理 像我脸一样黑的解决方案  Fiddler https 证书问题     ...

  8. 算法实现之python篇

    Python source code: gradient_boosting_regression.py from sklearn import ensemblefrom sklearn.metrics ...

  9. 52e174ef38c96afbbeabe55d2ec53622 我知道这是什么

    52e174ef38c96afbbeabe55d2ec53622   我知道这是什么52e174ef38c96afbbeabe55d2ec53622   我知道这是什么52e174ef38c96afb ...

  10. Codeforces 768A Oath of the Night's Watch

    A. Oath of the Night's Watch time limit per test:2 seconds memory limit per test:256 megabytes input ...