selenium Selify Web驱动程序(driver.find_Element(By.XPATH,‘’))不能使用Python

kd3sttzy  于 2022-11-10  发布在  Python
关注(0)|答案(1)|浏览(193)

https://www.espncricinfo.com/player/aamer-jamal-793441这是URL,我正在尝试访问全名“Aamer Jamal”。借助于Selify Web驱动程序。但我不知道为什么它会给

NoSuchElementException

`代码如下:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium_firefox import Firefox
import time
import pandas as pd

driver = webdriver.Firefox()

# Reach to the Landing page

driver.get('https://www.espncricinfo.com/player/aamer-jamal-793441')
driver.maximize_window()

time.sleep(25)
not_now = driver.find_element(By.ID, 'wzrk-cancel')
not_now.click()

fullname = driver.find_element(By.XPATH, '/html/body/div[1]/section/section/div[4]/div[2]/div/div[1]/div/div/div[1]/div[1]/span/h5')
print(fullname.text)`

错误:

NoSuchElementException: Message: Unable to locate element: /html/body/div[1]/section/section/div[4]/div[2]/div/div[1]/div/div/div[1]/div[1]/span
3pmvbmvn

3pmvbmvn1#

您必须使用WebDriverWaitexpected_conditions显式等待,而不是长时间的硬编码暂停。您还必须学习如何创建正确的定位器。长的绝对XPath和CSS选择器是极易破坏的。以下代码可以正常工作:

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")

webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(options=options, service=webdriver_service)
wait = WebDriverWait(driver, 60)
actions = ActionChains(driver)

url = "https://www.espncricinfo.com/player/aamer-jamal-793441"

driver.get(url)

wait.until(EC.element_to_be_clickable((By.ID, 'wzrk-cancel')))
fullname = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'ds-text-title-l'))).text
print(fullname)

输出为:

Aamer Jamal

相关问题