【问题标题】:Unable to locate elements in Selenium (using xpath) python within Instagram无法在 Instagram 中的 Selenium(使用 xpath)python 中定位元素
【发布时间】:2021-12-25 16:42:55
【问题描述】:

我正在尝试使用 selenium 单击一个元素,但由于某种原因,我在使用 Xpath 时一直遇到此错误。

from time import sleep
from selenium import webdriver

driver_path = "C:\WebDrivers\chromedriver"
driver = webdriver.Chrome(driver_path)
driver.implicitly_wait(5)
driver.get('https://www.instagram.com/accounts/login/?source=auth_switcher')

sleep(2)

username = driver.find_element_by_name('username')
username.send_keys('YourEmail')
password = driver.find_element_by_name('password')
password.send_keys('YourPassword')

submit =driver.find_element_by_tag_name('form')
submit.submit()

driver.implicitly_wait(15)

explore = driver.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[3]/div/div[4]/a/svg/path')
explore.click()

问题出现在我的最后两行代码中。 Xpath 来自以下 html 行:

<path clip-rule="evenodd" d="M24 0C10.8 0 0 10.8 0 24s10.8 24 24 24 24-10.8 24-24S37.2 0 24 0zm0 45C12.4 45 3 35.6 3 24S12.4 3 24 3s21 9.4 21 21-9.4 21-21 21zm10.2-33.2l-14.8 7c-.3.1-.6.4-.7.7l-7 14.8c-.3.6-.2 1.3.3 1.7.3.3.7.4 1.1.4.2 0 .4 0 .6-.1l14.8-7c.3-.1.6-.4.7-.7l7-14.8c.3-.6.2-1.3-.3-1.7-.4-.5-1.1-.6-1.7-.3zm-7.4 15l-5.5-5.5 10.5-5-5 10.5z" fill-rule="evenodd"></path>

我不确定,但这可能与它在&lt;svg&gt; 下的子类别有关

看截图:

【问题讨论】:

    标签: python selenium svg xpath css-selectors


    【解决方案1】:

    所需元素位于&lt;svg&gt; 标记内,因此要单击该元素,您可以使用以下任一Locator Strategies

    • 使用css_selector

      driver.find_element(By.CSS_SELECTOR, "svg[aria-label='Find People'] > path[clip-rule='evenodd'][fill-rule='evenodd']").click()
      
    • 使用xpath

      driver.find_element(By.XPATH, "//*[name()='svg' and @aria-label='Find People']//*[name()='path' and @clip-rule='evenodd']").click()
      

    理想情况下,您需要为element_to_be_clickable() 诱导WebDriverWait,您可以使用以下任一Locator Strategies

    • 使用CSS_SELECTOR:

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "svg[aria-label='Find People'] > path[clip-rule='evenodd'][fill-rule='evenodd']"))).click()
      
    • 使用XPATH

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[name()='svg' and @aria-label='Find People']//*[name()='path' and @clip-rule='evenodd']"))).click()
      
    • 注意:您必须添加以下导入:

      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC
      

    参考文献

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

    【讨论】:

      猜你喜欢
      • 2021-02-28
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      • 2016-09-17
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      相关资源
      最近更新 更多