1. 程式人生 > >Python selenium爬蟲抓取船舶網站資料(動態頁面)

Python selenium爬蟲抓取船舶網站資料(動態頁面)

很早之前就開始學習爬蟲了,一直想學習爬取動態頁面,正巧工作中需要用到一個船舶資訊的網站,每次都是手動查詢太麻煩了,昨天下午研究了一下午,總算搞透徹了,基本步驟如下:
1、啟動瀏覽器
2、開啟網頁
3、模擬輸入,模擬點選
4、稍等一會(很重要)
5、獲取網頁資料
6、清洗資料

程式碼分兩部分,一部分儲存為函式(Chrome_shipxy.py),另一部分作為程式呼叫函式,這樣方便擴充套件多程序使用。

from selenium.webdriver.common.keys import Keys
from selenium import webdriver
import time

def
func01(html):
#拆分字串 line='';html2=[];bj=0; for j in range(0,len(html)): if bj==0 and html[j:j+1]=='<': line=line+html[j:j+1];bj=1;continue if html[j:j+1]!='<': line=line+html[j:j+1];continue if bj==1 and html[j:j+1]=='<': html2.append(line); line=''
;line=line+html[j:j+1];bj=1; html2.append(line);line=''; return html2 def func02(html2): #篩選需要資訊 sxzd=['si_mmsiFlag','si_shipType','si_shipStatus','si_length','si_beam','si_lat','si_lng','si_lastTime']; #國籍,型別,狀態,船長,船寬,緯度,經度,最後時間 wb1=[];wb2=[]; for i in sxzd: bj=0; for
j in html2: if i in j: wb1.append(j);bj=1; if bj==0: wb1.append('>無資訊'); for j in wb1: for i in range(0,len(j)): if j[i:i+1]=='>': wb2.append(j[i+1:len(j)]) return wb2 def func03(ship_name,wait_time): #主函式 obj = webdriver.Chrome() obj.set_page_load_timeout(10) try: obj.get('http://www.shipxy.com/') obj.set_page_load_timeout(20) obj.find_element_by_id('txtKey').clear() #用於清除輸入框的內容,相當於clear() obj.find_element_by_id('txtKey').send_keys(ship_name) #在輸入框內輸入Hello obj.find_element_by_id('butnQuery').send_keys(Keys.ENTER) #通過定位按鈕,通過enter(回車)代替click time.sleep(wait_time) #讓子彈飛一會兒(很重要) html = obj.page_source time.sleep(2) html2=func01(html) html3=func02(html2) html3.insert(0,ship_name) except Exception as e: html3=['未獲取到資訊','無資訊'];#print(e); finally: obj.close() obj.quit() return html3
import Chrome_shipxy

if __name__=='__main__':

    ship_name=['SHINANO MARU','SEROJA LIMA','寶鑫通','桂翔1','嘉遠3','建功308','順恩','西馬11','鑫源盛','興達888','興寧20','豫信貨12262','忠泰'];
    for j in ship_name:
        html3=Chrome_shipxy.func03(j,5)
        if '無資訊' in html3[1]:
            for i in range(6,31,2):
                html3=Chrome_shipxy.func03(j,i)
                if '無資訊' not in html3[1]:
                    break
        print(html3)