使用selenium Python查找元素?

s3fp2yjn  于 2023-06-25  发布在  Python
关注(0)|答案(1)|浏览(137)

我想从以下位置找到搜索文本区域:https://1xbet.whoscored.com/
我在colab中使用了以下代码

from selenium import webdriver
from selenium.webdriver.common.by import By

# Initialize the webdriver
service = Service(executable_path=r'/usr/bin/chromedriver')
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
browser = webdriver.Chrome(service=service, options=options)
# Navigate to a webpage
browser.get('https://1xbet.whoscored.com/')

element = browser.find_element(By.XPATH,'//*[@id="search-box"]')

element.clear()
element.send_keys('Manchester united')

# Close the driver
browser.quit()

但是,它会引发以下错误

---------------------------------------------------------------------------
NoSuchElementException                    Traceback (most recent call last)
<ipython-input-130-cd823d469a61> in <cell line: 13>()
     11 browser.get('https://1xbet.whoscored.com/')
     12 
---> 13 element = browser.find_element(By.XPATH,'//*[@id="search-box"]')
     14 element.clear()
     15 element.send_keys('Manchester united')

2 frames
/usr/local/lib/python3.10/dist-packages/selenium/webdriver/remote/errorhandler.py in check_response(self, response)
    243                 alert_text = value["alert"].get("text")
    244             raise exception_class(message, screen, stacktrace, alert_text)  # type: ignore[call-arg]  # mypy is not smart enough here
--> 245         raise exception_class(message, screen, stacktrace)

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="search-box"]"}
  (Session info: headless chrome=112.0.5615.49); For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception

有什么建议吗?!

44u64gxh

44u64gxh1#

所需元件是动态元件。因此,要在元素中发送字符序列,您需要为element_to_be_clickable()引入WebDriverWait,您可以使用以下locator strategies之一:

  • 使用 CSS_SELECTOR
driver.get("https://1xbet.whoscored.com/")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#search-box[value='Search']"))).send_keys("Manchester united")
  • 使用 XPATH
driver.get("https://1xbet.whoscored.com/")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='search-box' and @value='Search']"))).send_keys("Manchester united")

*注意:需要添加以下导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
  • 浏览器快照:

参考资料

您可以在以下位置找到一些关于NoSuchElementException的相关讨论:

相关问题