山东创睦网络科技有限公司:Python小爬虫 爬取整站

我是一只放养的小爬虫–拉钩网半智能整站小爬虫
笔者声明:只用于学习交流,不用于其他途径。源代码已上传github。githu地址:https://github.com/Erma-Wang/Spider

Python写爬虫的感觉那叫一个爽!100行代码不到,爬取整站,貌似这样下去拉钩还不加强服务器么?下面看看半智能的效果,程序员嘛。。。不做外壳了。。。我只是一只放养的小爬虫,拉钩看到就说对不起啰!!。哈哈,下面看图:

在这里插入图片描述

输入命令后,小爬虫开始工作了!
1
爬去结束后小爬虫自动生成了一个XLS文件,一般的excel就能打开了
1

最后看看成果:
1

好了,效果看完了,看看小爬虫怎么制造出来的吧。。。
其中也没有什么难点的技术,不过pandas很值得学习,给个学习链接http://pandas.pydata.org,挺不错的。。下面贴一下代码吧。。。github上面也有。

-- coding:utf-8 --

import re,json
from urllib import request
from pandas import DataFrame,Series
import pandas as pd

author = “放养的小爬虫”

处理字符串的函数

def ProcessingString(string):
string = string.encode(‘utf-8’)
string = str(string).replace(r’\x’,’%’).replace(r"’","")
string = re.sub(’^b’,’’,string)
return string

计算总共页数

def SearchPageCount(position, city):
i = 0
type = ‘true’
url = ‘http://www.lagou.com/jobs/positionAjax.json?city=’+city+’&first=’+type+’&kd=’+position+’&pn=’+str(i+1)
with request.urlopen(url) as f:
data = f.read()
count = int(json.loads(str(data,encoding=‘utf-8’,errors=‘ignore’))[“content”][“totalPageCount”])
totalCount = int(json.loads(str(data,encoding=‘utf-8’,errors=‘ignore’))[“content”][“totalCount”])
print(‘本次搜索到%d个职位’%totalCount)
return count

def LaGouSpiderWithKeyWord(position, city):
positionTemp = ProcessingString(position)
cityTemp = ProcessingString(city)

获取总共页数

pageCount = SearchPageCount(positionTemp,cityTemp)

for i in range(0,pageCount):
if i ==0 :
type=‘true’
else:
type=‘false’
url = ‘http://www.lagou.com/jobs/positionAjax.json?city=’+cityTemp+’&first=’+type+’&kd=’+positionTemp+’&pn=1’
data = request.urlopen(url).read()

读取Json数据

jsondata = json.loads(str(data,encoding='utf-8',errors='ignore'))['content']['result']
for t in list(range(len(jsondata))):
    jsondata[t]['companyLabelListTotal']='-'.join(jsondata[t]['companyLabelList'])
    jsondata[t].pop('companyLabelList')
    if t == 0:
        rdata=DataFrame(Series(data=jsondata[t])).T
    else:
        rdata=pd.concat([rdata,DataFrame(Series(data=jsondata[t])).T])
if i == 0:
    totaldata=rdata
else:
    totaldata=pd.concat([totaldata,rdata])
print('正在解析第%d页...'%i)

totaldata.to_excel(‘lagou.xls’,sheet_name=‘sheet1’)

if name == “main”:
position = input(‘请输入你要爬取的职位’)
city = input(‘请输入你要爬取的城市’)
LaGouSpiderWithKeyWord(position, city)
作者声明:只做学习交流,不用于其他途径!!!

Do you want to spend the rest of your life selling sugared water or do you want a chance to change the world?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值