2023年10月1日 星期日

爬蟲遊戲-傳訊往

 


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import WebDriverWait
import time

# '設定驅動'
driver = webdriver.Chrome()
# 設定隱性等待
# driver.implicitly_wait(10)


def go_url(inp_url):
    '到指定的url'
    driver.get(inp_url)


def localation_ele(web_xpath):
    '定位元素'
    '設置顯性等待'
    elem = WebDriverWait(driver, 10).until(
        ec.presence_of_element_located((By.XPATH, web_xpath)))
    return elem


def contral_ele(element, string):
    '先清除元素預留資料'
    element.clear()
    element.send_keys(string)


def user_click(ele):
    '模擬點擊'
    ele.click()


go_url('https://www.shipxy.com/Home/Login')  # 進到登入頁面
'定位帳號欄位'
'點擊帳號密碼登入'
logg = localation_ele('//*[@id="loginBoxWeixin"]/p[3]/a[1]')
user_click(logg)

user = localation_ele('//*[@id="userName"]')
'輸入帳號'
contral_ele(user, '輸入帳號')
pw = localation_ele('//*[@id="userPWD"]')
contral_ele(pw, '輸入密碼')

'定位登入'
login = localation_ele('//*[@id="loginBtn"]')
user_click(login)
'重新導向url'
go_url('https://www.shipxy.com')


'根據記事本內的資料查詢'
with open('新文字文件.txt', 'r')as file:
    data = file.read()
rows = data.split()
print(f'檔案資料={rows}')

for row in rows:
    ship_data = []
    print(f'正在查詢{row}')
    inp_ship = localation_ele('//*[@id="txtKey"]')
    contral_ele(inp_ship, row)
    search_but = localation_ele('//*[@id="searchBtn"]')
    user_click(search_but)
    time.sleep(2)
    # 由於設置了顯示等待仍然會發現資料位加載完成,所以只好使用time.sleep()

    mmsi = localation_ele('//*[@id="si_mmsi"]').text
    lat = localation_ele('//*[@id="si__lat"]').text
    long = localation_ele('//*[@id="si__lon"]').text
    position_time = localation_ele('//*[@id="si_lastTime"]').text
    eta_place = localation_ele('//*[@id="si_dest"]').text
    eta = localation_ele('//*[@id="si__eta"]').text
    ship_data = ['輸入的mmsi: ', row, '\n', '查到的mmis: ', mmsi, '\n', '緯度: ', lat, '\n', '經度: ',
                 long, '\n', '點位時間: ', position_time, '\n', 'eta位置: ', eta_place, '\n', 'eta: ', eta, '\n']

    with open('ship_data.txt', 'a')as file:
        file.writelines(ship_data)

標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁