我正在嘗試自動化
所有這些錢包都共享同一個類elements__StyledListItem-sc-197zmwo-0 QbTKh,我撰寫了下面的代碼以嘗試獲取它們的按鈕名稱(Metamask,Coinbase 錢包......),在這里:
driver = webdriver.Chrome(service=s, options=opt) #execute the chromedriver.exe with the previous conditions
driver.implicitly_wait(10)
driver.get('https://opensea.io/') #go to the opensea main page.
WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="__next"]/div/div[1]/nav/ul/div[2]/li/button'))) #wait for the wallet button to be enabled for clicking
wallet_button = driver.find_element(By.XPATH, '//*[@id="__next"]/div/div[1]/nav/ul/div[2]/li/button')
wallet_button.click() #click that wallet button
wallet_providers = driver.find_elements(By.CLASS_NAME, "elements__StyledListItem-sc-197zmwo-0 QbTKh") #get the list of wallet providers
for i in wallet_providers:
print(i)
編譯上面的代碼后,我注意到它沒有列印任何東西,這是由于 的空陣列wallet_providers,這很奇怪,因為我知道通過呼叫find_elements(By.CLASS_NAME, "the_class_name")它將回傳一個包含共享同一類元素的陣列,但在這種情況下并沒有這樣做。
所以,如果有人能解釋我做錯了什么,我將不勝感激?最后,我只是想設法單擊 Metamask 按鈕,它并不總是停留在同一位置,有時它是該串列的第一個元素,有時是第二個元素......
uj5u.com熱心網友回復:
您正在使用其中有空間的CLASS_NAME 。 elements__StyledListItem-sc-197zmwo-0 QbTKh
在 Selenium 中,包含空格的類名將不會被決議并會拋出錯誤。
您沒有收到錯誤的原因是因為您正在使用find_elements它將回傳 Web 元素串列或不回傳任何內容。
那么如何解決這個問題呢?
洗掉空間并放置 a.來代替CSS_SELECTOR
試試這個:
wallet_providers = driver.find_elements(By.CSS_SELECTOR, ".elements__StyledListItem-sc-197zmwo-0.QbTKh") #get the list of wallet providers
老實說,我們可以有比這更好的定位器,因為這些值似乎197zmwo-0.QbTKh是動態生成的。
我寧愿使用這個CSS:
li[class^='elements__StyledListItem'] span[font-weight]
或者這個xpath:
//li[starts-with(@class,'elements__StyledListItem')]//descendant::span[@font-weight]
此外,您應該像這樣列印它:(這是一種方式,但也有其他方式):
代碼:
driver.get("https://opensea.io/")
WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="__next"]/div/div[1]/nav/ul/div[2]/li/button'))) #wait for the wallet button to be enabled for clicking
wallet_button = driver.find_element(By.XPATH, '//*[@id="__next"]/div/div[1]/nav/ul/div[2]/li/button')
wallet_button.click() #click that wallet button
wallet_providers = driver.find_elements(By.CSS_SELECTOR, "li[class^='elements__StyledListItem'] span[font-weight]") #get the list of wallet providers
for i in wallet_providers:
print(i.get_attribute('innerText'))
控制臺輸出:
WalletConnect
MetaMask
Coinbase Wallet
Fortmatic
Process finished with exit code 0
uj5u.com熱心網友回復:
您使用的定位器不夠相關,在我第一次檢查時,我不知何故沒有在 DOM 中找到它們。因此,使用相對定位符重構代碼以使代碼正常作業。
driver.get('https://opensea.io/') #go to the opensea main page.
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//*[@title='Wallet']"))).click()
wallets = WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.XPATH, "//*[@data-testid='WalletSidebar--body']//li")))
for wallet in wallets:
print(wallet.text)
輸出:
WalletConnect
MetaMask
Popular
Coinbase Wallet
Fortmatic
Process finished with exit code 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/417975.html
標籤:
