python - 无法在 Instagram 中的 Selenium(使用 xpath)python 中定位元素
问题描述
我正在尝试使用 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>
我不确定,但这可能与它被归类为以下事实有关<svg>
看截图:
解决方案
所需元素位于<svg>
标签内,因此要单击该元素,您可以使用以下任一定位器策略:
使用
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()
理想情况下,您需要诱导WebDriverWait并且element_to_be_clickable()
您可以使用以下任一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
参考
您可以在以下位置找到一些相关的详细讨论:
推荐阅读
- html - Bootstrap:表单控件无响应
- visual-studio - 在 Visual Studio 2017 和 ssis 中苦苦挣扎
- java - 我们应该在 Spring Boot 中为存储库层编写单元测试和集成测试吗?
- android-fragments - 为什么引起:java.lang.IllegalStateException:surface_view 不能为空?
- matlab - 矢量插值返回相同的值
- c++ - 使用返回类型调用模板化指向成员函数时出错
- php - HTACCESS REDIRECT 301 延迟
- regex - 正则表达式 - 文件名与所需模式不匹配
- git - 如何从 Execute Shell 引用 Jenkins Github 存储库名称?
- angular - 我想使用带有验证器的反应式表单一次显示一个错误