python爬虫——拉钩网职位(scrapy)

<strong>上一篇python爬虫——拉钩网职位信息文章中提到要用scrapy框架去完成这个工作,现在已基本完成,自己可以添加更多职位和城市。
思路和上一篇文章用requests+beautifulsoup一样,不同的是上一次写的是csv格式文件,这次存入mysql数据库,废话不多说直接上代码</strong>

1.items.py

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

# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html

import scrapy


class LagouzpItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    city = scrapy.Field()
    company_name = scrapy.Field()
    size = scrapy.Field()
    edu = scrapy.Field()
    financeStage = scrapy.Field()
    firstType = scrapy.Field()
    industryField = scrapy.Field()
    name = scrapy.Field()
    salary = scrapy.Field()
    secondType = scrapy.Field()
    workYear = scrapy.Field()
    time = scrapy.Field()

2.pipeline.py

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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import MySQLdb
import csv

class LagouzpPipeline(object):
    #写文件
    # def __init__(self):
    #     with open("data.csv", "ab+") as self.files:
    #         self.write = csv.writer(self.files)
    #         self.write.writerow(
    #             ['职位名称', '公司名称', '城市', '公司规模', '公司类型', '月薪', '行业领域', 'firstType', 'senondType', '工作经历', '学历', '发布时间'])
    #
    # def process_item(self, item, spider):
    #     with open("data.csv", "ab+") as self.files:
    #         self.write = csv.writer(self.files)
    #         self.line = [item['name'], item['city'], item['company_name'], item['size'], item['financeStage'],item['salary'], item['industryField'], item['firstType'],item['secondType'],item['workYear'],item['edu'],item['time']]
    #         self.write.writerow(self.line)
    #     return item
    #数据库
    def __init__(self):
        self.conn = MySQLdb.connect(user='root', passwd='123456', db='lagou', host='localhost', charset='utf8',
                                    use_unicode=True)
        self.cursor = self.conn.cursor()

    def process_item(self, item, spider):
        self.cursor.execute(
            "insert into jobinfo(name,city,company,size,type,salary,field,firsttype,secondtype,workyear,edu,time) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",(item['name'], item['city'], item['company_name'], item['size'], item['financeStage'],item['salary'], item['industryField'], item['firstType'],item['secondType'],item['workYear'],item['edu'],item['time'],))
        self.conn.commit()
        return item


<em>这里分别提到了文件的操作和数据库的操作方式,可以参考一下
</em>

3.lg_spider.py

# -*- coding:utf-8 -*-
import scrapy
from ..items import LagouzpItem
import requests
from bs4 import BeautifulSoup
import json

class Spider(scrapy.Spider):
    name = 'lagou'
    cookies = {
        'user_trace_token': '20170314211704-f55f18938db84cfeae95d1efec6d585e',
        'LGUID': '20170314211706-859943f0-08b8-11e7-93e0-5254005c3644',
        'JSESSIONID': 'AA1DE67564F4C20F86F89F3572B706A1',
        'PRE_UTM': '',
        'PRE_HOST': 'www.baidu.com',
        'PRE_SITE': 'https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3DuQkzN6ld65B8UHLJeaN2RVwWb3jiAl6AkSQSZRkXpRC%26wd%3D%26eqid%3Df6aa96cc0000dd5e0000000258ff3f34',
        'PRE_LAND': 'https%3A%2F%2Fwww.lagou.com%2F',
        'index_location_city': '%E5%85%A8%E5%9B%BD',
        'Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6': '1491116405,1491116452,1493122880,1493122898',
        'Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6': '1493123186',
        '_ga': 'GA1.2.1412866745.1489497427',
        'LGSID': '20170425202132-b7ea71dc-29b1-11e7-bc70-525400f775ce',
        'LGRID': '20170425202620-6394f6bd-29b2-11e7-bc72-525400f775ce',
        'TG-TRACK-CODE': 'search_code',
        'SEARCH_ID': '63e7755cfbbf40559a5dac6a35e5f49f'
    }
    headers = {
        "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"}
    def start_requests(self):
        kd = ['python工程师', 'python数据分析']
        city = ['北京', '上海', '深圳', '广州', '杭州', '成都', '南京', '武汉', '西安', '厦门', '长沙', '苏州', '天津']
        urls_kd = ['https://www.lagou.com/jobs/list_{}?px=default&city='.format(one) for one in kd]
        for urls in urls_kd:
            urls_city = [urls + one for one in city]
            for url in urls_city:
                response = requests.get(url, headers=self.headers, cookies=self.cookies)
                location = url.split('&')[-1].split('=')[1]
                key = url.split('/')[-1].split('?')[0].split('_')[1]
                soup = BeautifulSoup(response.text, 'lxml')
                pages = soup.find('span', {'class': 'span totalNum'}).get_text()
                for i in range(1, int(pages) + 1):
                    url = 'https://www.lagou.com/jobs/positionAjax.json?px=default&city={}&needAddtionalResult=false'.format(location)
                    formdata = {
                        'first': 'true',
                        'pn': str(i),
                        'kd': key
                    }
                    print u'正在获取职位——{},城市{},第{}页数据'.format(key,location,i)
                    yield scrapy.FormRequest(url,formdata=formdata,cookies=self.cookies,callback=self.parse)
    def parse(self, response):
        data = json.loads(response.text)
        content = data['content']
        positionResult = content['positionResult']
        item = LagouzpItem()
        for one in positionResult['result']:
            try:
                item['city'] = one['city']
            except:
                item['city'] = u''
            try:
                item['company_name'] = one['companyFullName']
            except:
                item['company_name'] = u''
            try:
                item['size'] = one['companySize']
            except:
                item['size'] = u''
            try:
                item['edu'] = one['education']
            except:
                item['edu'] = u''
            try:
                item['financeStage'] = one['financeStage']
            except:
                item['financeStage'] = u''
            try:
                item['firstType'] = one['firstType']
            except:
                item['firstType'] = u''
            try:
                item['industryField'] = one['industryField']
            except:
                item['industryField'] = u''
            try:
                item['name']= one['positionName']
            except:
                item['name'] = u''
            try:
                item['salary'] = one['salary']
            except:
                item['salary'] = u''
            try:
                item['secondType'] = one['secondType']
            except:
                item['secondType'] = u''
            try:
                item['workYear'] = one['workYear']
            except:
                item['workYear'] = u''
            try:
                item['time'] = one['createTime'].split(' ')[0]
            except:
                item['time'] = u''
            yield item

<em>这里用scrapy.FormRequest()直接提交表单数据,怕出错全部 try...except 后来想了一下感觉没多大必要</em>

4.结果

职位信息

总结

<strong>用哪种方式实现不重要,思路一定要清晰正确,再挖一个坑——用类封装之前python爬虫——拉钩网职位信息的函数,可以更加规范,尝试加多线程。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容