【问题标题】:Can't locate element by xpath in selenium?在 selenium 中无法通过 xpath 定位元素?
【发布时间】:2020-04-02 05:12:34
【问题描述】:

我现在正在通过制作一个小脚本来学习 python 和 selenium,该脚本将生日 cmets 发布给我的 facebook 朋友。我能够成功登录并导航到“朋友的生日”模式,但是我无法在文本框中发表评论。

这是我得到的错误:

selenium.common.exceptions.NoSuchElementException: 
Message: no such element: Unable to locate element:
{"method":"xpath","selector":"//*[@id="u_i_6"]"}

我在通过 XPath 查找其他页面元素时没有遇到任何问题,所以我不确定是什么导致了问题。我还尝试通过类名查找要评论的文本框,但结果相同。谁能提供一些想法?

编辑:忘记粘贴代码

from selenium import webdriver
from pynput.keyboard import Key, Controller
import time
import config
# fetch facebook password from separate file in the same directory
pw = config.secret['pw']
keyboard = Controller()

driver = webdriver.Chrome()
options = webdriver.ChromeOptions()
options.add_argument('--disable-extensions')
options.add_argument('--disable-notifications')

# navigate to facebook url
driver.get('https://facebook.com')

# input email address
email_input = driver.find_element_by_xpath('//*[@id="email"]')
email_input.send_keys(<omitted>)
# input pw
password_input = driver.find_element_by_xpath('//*[@id="pass"]')
password_input.send_keys(pw)
# click login button element
login_button = driver.find_element_by_xpath('//*[@id="u_0_b"]')
login_button.click()

home_button = driver.find_element_by_xpath('//*[@id="u_0_c"]/a')
# wait 8 seconds for browser popup before pressing esc to get out
time.sleep(8)
keyboard.press(Key.esc)

# check if there are any birthdays today
birthday_section = driver.find_element_by_xpath('//*[@id="home_birthdays"]/div/div/div/div/a/div/div/span/span[1]')
birthday_section.click()

first_comment = driver.find_element_by_xpath('//*[@id="u_i_6"]')
first_comment.send_keys('happy birthday!')
# click post button to post comment

# close browser window after actions are complete
time.sleep(5)
driver.close()

【问题讨论】:

  • 使用 webdriverwait 或者检查 iframe 的存在来定位你的元素
  • 请发布您的代码

标签: python selenium selenium-webdriver xpath nosuchelementexception


【解决方案1】:

没有代码很难回答,但这里有几个想法:

  1. 确保您使用某种Selenium wait,隐式或显式,因此您的代码不会在该元素出现在页面上之前搜索该元素。您可以在driver.get() 之后添加此代码以进行隐式等待:
driver.implicitly_wait(5)
  1. 此外,该页面上的 ID 似乎是动态的,我在我的 FB 页面上得到了一个不同的 ID。尝试使用此xpath 查找文本区域:
"//form[contains(@action, 'birthday')]//textarea"

希望对你有帮助,祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多