1. 程式人生 > >一個簡單Python爬蟲例項(爬取的是前程無憂網的部分招聘資訊)

一個簡單Python爬蟲例項(爬取的是前程無憂網的部分招聘資訊)

從今天開始學習爬蟲,展示我的第一個例項(用的是Python3寫的,Python2需要加個編碼方式吧,或許還有其他的不相容的地方吧,我就不知道了),把這分享給大家,希望對大家有一些幫助

import urllib,re
import urllib.request
import xlwt
#開啟網頁,獲取原始碼

def get_content():
    url='https://search.51job.com/list/170200,000000,0000,00,9,99,Python,2,1.html?lang=c&stype=&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=99&companysize=99&providesalary=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0&address=&line=&specialarea=00&from=&welfare='
    a=urllib.request.urlopen(url)#開啟網站
    html=a.read()
    html=html.decode('gbk')#解碼
    print(html)
    return html
#從原始碼中獲取資料
def get():
    html=get_content()
    reg=re.compile(r'class="t1 ".*?<a target="_blank" title="(.*?)".*?<span class="t2"><a target="_blank" title="(.*?)".*? <span class="t3">(.*?)</span>.*? <span class="t4">(.*?)</span>.*? <span class="t5">(.*?)</span>',re.S)#提高效率
    items=re.findall(reg,html)
    print(items)
    return items
#建立Excel表格
def excel_write(items):
    newTable='test.xls'
    wb=xlwt.Workbook(encoding='utf-8')#建立表格
    ws=wb.add_sheet('test1')
    headData=['招聘職位','公司','地址','薪資','日期']
    for colnum in range(0,5):
        ws.write(0,colnum,headData[colnum],xlwt.easyxf('font:bold on'))
    index=1
    for item in items:
        for i in range(0,5):
            ws.write(index,i,item[i])
        index+=1
        wb.save(newTable)
    
items=get()
excel_write(items)