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

看板Python作者 (MBD)時間6年前 (2019/06/02 00:25), 編輯推噓6(605)
留言11則, 5人參與, 6年前最新討論串1/1
最近在學習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呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.242.142.44 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1559406349.A.DFF.html

06/02 02:58, 6年前 , 1F
你跳關了,先把語言本身的語法基礎弄懂再來搞爬蟲之類
06/02 02:58, 1F

06/02 02:58, 6年前 , 2F
06/02 02:58, 2F

06/02 07:28, 6年前 , 3F
基本觀念走一次
06/02 07:28, 3F

06/02 07:32, 6年前 , 4F
似乎是要多用一層小括號把你的 3 個引數包起來
06/02 07:32, 4F

06/02 08:11, 6年前 , 5F
又好像是呼叫 BasePage 時需要先加一個 driver 的引數?
06/02 08:11, 5F

06/02 10:49, 6年前 , 6F
你的BasePage沒有建出instance 所以少傳一個self
06/02 10:49, 6F

06/02 10:51, 6年前 , 7F
同一樓 你要先把變數、類別這章再讀過一遍
06/02 10:51, 7F

06/02 10:52, 6年前 , 8F
看完後你就會發現 要傳進去的是LocatorMode裡的member
06/02 10:52, 8F

06/02 10:56, 6年前 , 9F
然後你可能會遇到sean大提到的問題 把類別這章讀熟吧
06/02 10:56, 9F

06/02 15:05, 6年前 , 10F
這種少了第一個參數,但錯誤訊息卻是說你少了最後一個參數
06/02 15:05, 10F

06/02 15:06, 6年前 , 11F
對類別不熟的人就會被誤導了
06/02 15:06, 11F
文章代碼(AID): #1SygSDt_ (Python)
文章代碼(AID): #1SygSDt_ (Python)