美文网首页大数据 爬虫Python AI SqlPython学习分享
Python在手,天下我有!Python 爬虫入门-爬取拉勾网实

Python在手,天下我有!Python 爬虫入门-爬取拉勾网实

作者: 烟雨丿丶蓝 | 来源:发表于2019-06-17 15:11 被阅读16次

    一、基本思路

    1、向服务器发送请求,服务器响应你的请求

    2、从抓取到的网页中提取出需要的数据,需要了解的知识点:正则表达式、Beautifulsoup。

    3、保存数据并存储

    当然,有以上功能还是不够的,你还需要与网站反爬策略斗智斗勇:(仅供参考)

    1、构造合理的请求头

    2、设置cookie

    3、正常的时间访问路径

    二、项目实战

    1、首先打开拉勾网,并搜索“数据分析”,设置工作地点“合肥”,显示出来的职位便是我们的目标

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

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

    (2)异步加载的信息,我们需要借助chrome浏览器的小工具进行分析,按F12即可打开,界面如下:

    image

    (3)点击Network进入网络分析界面,这时候是一片空白,刷新一下界面就可以看到一系列的网络请求了,正常我们可以忽略css,png等类型的请求,关注点放在xhr这种类型请求上,如下:

    image

    (4)在Network标签中可以分析网站的请求响应过程,这里看到Network标签下 Type为xhr里有companyAjax.json和 positionAjax.json,点击其中任一个,然后再点击Headers下拉到底部,这里我们可以肯定city参数便是城市,pn参数便是页数,kd参数便是职位关键字

    image

    三、代码部分

    <pre style="margin: 0px; padding: 0px; border: 0px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-variant-numeric: inherit; font-variant-east-asian: inherit; font-weight: 400; font-stretch: inherit; font-size: 18px; line-height: inherit; font-family: inherit; vertical-align: baseline; word-break: break-word; color: rgb(93, 93, 93); letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-style: initial; text-decoration-color: initial;">

    # 导入第三方库
    import requests
    import time
    import xlwt
    import random
    from fake_useragent import UserAgent
    def get_html():
     k = 1 # 参数k代表存储到excel的行数
     wb = xlwt.Workbook() # 创建工作簿
     f = wb.add_sheet("招聘信息") # 创建工作表
     '''
     下方的循环是将Excel表格中第一行固定 Excel表第一行的前十列分别对应 岗位id、公司全名、福利待遇、工作地点、学历要求、工作类型、发布时间、职位名称、薪资、工作年限 '''
     title = ['岗位id', '公司全名', '福利待遇', '工作地点', '学历要求', '工作类型', '发布时间', '职位名称', '薪资', '工作年限']
     for i in range(len(title)):
     f.write(0, i, title[i])
     '''
     write函数中第一个参数表示存储到多少行
     第二个参数存储到多少列,第三个参数代表存储到对应行列的值 '''
     url = 'https://www.lagou.com/jobs/positionAjax.json'
     try:
     for i in range(1, 3): # 设置爬取的页数
     datas = {
     'first': True,
     'pn': i,
     'kd': '数据分析',
     'city': '合肥'
     }
     # 生成随机头部信息
     ua = UserAgent()
     my_headers = {
     'User-Agent': ua.random,
     'Accept': 'application/json, text/javascript, */*; q=0.01',
     'Accept-Language': 'zh-CN,zh;q=0.8',
     'Host': 'www.lagou.com',
     'Origin': 'https://www.lagou.com',
     'Referer': 'https://www.lagou.com/jobs/list_%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90?city=%E5%90%88%E8%82%A5&cl=false&fromSearch=true&labelWords=&suginput=',
     }
     cookies = {'Cookie': 'user_trace_token=20180624215350-061eb778-77b6-11e8-9759-5254005c3644; LGUID=20180624215350-061ebd84-77b6-11e8-9759-5254005c3644; index_location_city=%E5%85%A8%E5%9B%BD; JSESSIONID=ABAAABAAAFCAAEGF1EF1B6010A330DBDBCCED5B882CB930; PRE_UTM=; PRE_HOST=; PRE_SITE=; PRE_LAND=https%3A%2F%2Fwww.lagou.com%2Fjobs%2Flist_Python%3Fcity%3D%25E5%2585%25A8%25E5%259B%25BD%26cl%3Dfalse%26fromSearch%3Dtrue%26labelWords%3D%26suginput%3D; _gid=GA1.2.1270343383.1529848434; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1529848456,1529848503,1529887134,1529997909; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1529997949; _ga=GA1.2.1753800450.1529848434; LGSID=20180626152503-0abfdc6e-7912-11e8-b0e7-525400f775ce; LGRID=20180626152543-22fce922-7912-11e8-b0e7-525400f775ce; SEARCH_ID=3a26153ea34a41f795e5d9f64fcfb236'}
     # 进程挂起的时间
     time.sleep(20 + random.randint(0, 20))
     content = requests.post(url=url, cookies=cookies, headers=my_headers, data=datas)
     if content.status_code == 200:
     result = content.json()
     info = result['content']['positionResult']['result']
     for job in info:
     f.write(k, 0, job['positionId'])
     f.write(k, 1, job['companyFullName'])
     f.write(k, 2, job['companyLabelList'])
     f.write(k, 3, job['district'])
     f.write(k, 4, job['education'])
     f.write(k, 5, job['firstType'])
     f.write(k, 6, job['formatCreateTime'])
     f.write(k, 7, job['positionName'])
     f.write(k, 8, job['salary'])
     f.write(k, 9, job['workYear'])
     k += 1 # 每存储一行 k值加1
     wb.save('C:/Users/Administrator/Desktop/lagou.xls')
     except TimeoutError:
     print('请求失败')
     return None
    if __name__=='__main__':
     get_html()
    
    

    </pre>

    此次的爬虫就分享到这里,如果你有任何问题,欢迎在留言区域表达你的疑惑;同时,也欢迎各位小伙伴转发与分享文中的内容,让更多的人学习与进步!

    在这推荐下小编创建的Python学习交流群835017344,可以获取Python入门基础教程,送给每一位小伙伴,这里是小白聚集地,每天还会直播和大家交流分享经验哦,欢迎初学和进阶中的小伙伴。


    相关文章

      网友评论

        本文标题:Python在手,天下我有!Python 爬虫入门-爬取拉勾网实

        本文链接:https://www.haomeiwen.com/subject/fcbafctx.html