[問題] 自訂function該輸入哪些變數?

作者: A601B8 (MBD)   2019-06-02 00:25:47
最近在學習selenium webdriver尋找元素時
常需要重複打
find_element_by_id或xpath或name等等....
如是還要加上explicit wait時
就會讓code變得又臭又常
剛好在逛論壇時看到有個網友PO了一個自訂function
======
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.select import Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from abc import abstractmethod
class LocatorMode:
XPATH = "xpath"
CSS_SELECTOR = "cssSelector"
NAME = "name"
ID = "id"
TAG_NAME = "tagName"
class BasePage(object):
def __init__(self, driver):
self.driver = driver
def wait_for_element_visibility(self, waitTime, locatorMode, Locator):
element = None
if locatorMode == LocatorMode.ID:
element = WebDriverWait(self.driver, waitTime).\
until(EC.visibility_of_element_located((By.ID, Locator)))
elif locatorMode == LocatorMode.NAME:
element = WebDriverWait(self.driver, waitTime).\
until(EC.visibility_of_element_located((By.NAME, Locator)))
elif locatorMode == LocatorMode.XPATH:
element = WebDriverWait(self.driver, waitTime).\
until(EC.visibility_of_element_located((By.XPATH, Locator)))
elif locatorMode == LocatorMode.CSS_SELECTOR:
element = WebDriverWait(self.driver, waitTime).\
until(EC.visibility_of_element_located((By.CSS_SELECTOR,
Locator)))
else:
raise Exception("Unsupported locator strategy.")
return element
=====
我試了好多次都沒辦法成功呼叫這個function
我現在希望的狀況是
1.用tagname來找element,且假設網頁中element的tagname="tr"
2.EC是在visibility_of_element_located的狀況
3.等待時間是10秒
所以我自己試了一下
element = BasePage.wait_for_element_visibility(10,tagName,"tr")
element.click()
但如果用這樣的input執行的話
系統會返回:
name 'tagName' is not defined
要是換成
element = BasePage.wait_for_element_visibility(10,"tagName","tr")
element.click()
系統會返回:
wait_for_element_visibility() missing 1 required positional argument:
'Locator'
請問我要怎麼輸入括號內的變數,才能成功執行BasePage裡面的function呢?
作者: CaptainH (Cannon)   2019-06-02 02:58:00
你跳關了,先把語言本身的語法基礎弄懂再來搞爬蟲之類的
作者: jiyu520 (不要鯽魚我)   2019-06-02 07:28:00
基本觀念走一次
作者: art1 (人,原來不是人)   2019-06-02 07:32:00
似乎是要多用一層小括號把你的 3 個引數包起來又好像是呼叫 BasePage 時需要先加一個 driver 的引數?
作者: sean50301 ( (づ′・ω・)づ)   2019-06-02 10:49:00
你的BasePage沒有建出instance 所以少傳一個self
作者: vi000246 (Vi)   2019-06-02 10:51:00
同一樓 你要先把變數、類別這章再讀過一遍看完後你就會發現 要傳進去的是LocatorMode裡的member然後你可能會遇到sean大提到的問題 把類別這章讀熟吧
作者: art1 (人,原來不是人)   2019-06-02 15:05:00
這種少了第一個參數,但錯誤訊息卻是說你少了最後一個參數對類別不熟的人就會被誤導了

Links booklink

Contact Us: admin [ a t ] ucptt.com