用PYTHON写的第一个爬虫程序,并以EXCEL格式保存
自己动手写的第一个Python爬虫,代码比较渣,大神略过。
# _*_ coding:utf-8 _*_
import requests,xlwt,json,time,random
items=[]
def get_content(pn):
url='https://www.lagou.com/jobs/positionAjax.json?needAddtionalResult=false' #提交的URL
data={'first':'true', #带参数提交
'pn':pn,
'kd':'python'}
html=requests.post(url,data).text #获取网页内容
html=json.loads(html) #转成JSON格式
for i in range(14):
item=[]
item.append(html['content']['positionResult']['result'][i]['positionName']) #职位名称
item.append(html['content']['positionResult']['result'][i]['salary']) #薪资
item.append(html['content']['positionResult']['result'][i]['companyFullName']) #公司名称
item.append(html['content']['positionResult']['result'][i]['workYear']) #要求
# print u'职位名称:%s 薪资:%s 公司名: %s 要求: %s'%item[0],%item[1],%item[2],%item[3]
print u'职位名称:%s\n'u'工资:%s\n' u'公司名称:%s\n'u'要求:%s\n'%(item[0],item[1],item[2],item[3])
items.append(item)
return items
def excel_write():
newtable='test.xls'#excel表名
wb=xlwt.Workbook(encoding='utf-8') #创建并设置表
ws=wb.add_sheet('text1') #创建表的名称
headData=['职位名称','薪资','公司名称','要求'] #设置EXCEL表头
for hd in range(0,4):
ws.write(0,hd,headData[hd],xlwt.easyxf('font:bold on ')) #第0行0例开始写入表头
id=1
index=1
while id<=4:
get_content(id)
id+=1
time.sleep(random.randrange(0,3))#随机休眠几秒防IP锁定
for item in items: #从列表数组里取一行
for i in range(0,4): #从item里取出每列的值
ws.write(index,i,item[i])
index+=1
wb.save(newtable)#保存并生成EXCEL
if __name__=="__main__":
excel_write()
print u'*****************共爬取并写入EXCEL数据%s条************'%len(items)

