如何获得 Selenium 点击位置的视觉指示?

问题描述 投票:0回答:2

我正在尝试按最新的顺序对 Facebook 上的帖子进行排序。当我单击“新活动”

driver.find_element_by_xpath("//*[contains(text(), 'New activity')]").click()
时,它的行为符合预期,打开一个下拉框。当我尝试单击“首先查看最近的帖子”时,它会抛出“不可迭代的错误”。我相信它的父元素是可点击元素,所以我尝试点击它。
driver.find_element_by_xpath("//*[contains(text(), 'See most recent posts first')]").find_element_by_xpath('..').click()
这就像我点击了网页的不同部分一样。我希望能通过一些视觉提示来了解 Selenium 的点击位置,以帮助调试此问题。如果有人对解决此问题的其他方法有建议,我将不胜感激。

设置代码:

    driver = webdriver.Chrome()        

    # Use this code to create your own cookie file:
    # driver.get("https://www.facebook.com")
    # time.sleep(60)
    # pickle.dump(driver.get_cookies() ,open("cookies.pkl","wb"))


    # Login using cookies bucs Facebooks login system is a pain to navigate in html. (Presumably to discourage
    # bots like me.)
    driver.get("https://www.facebook.com/groups/backstagetheatrejobs/")
    cookies = pickle.load(open("cookies.pkl", "rb"))
    for cookie in cookies:
        driver.add_cookie(cookie)
    driver.get("https://www.facebook.com/groups/backstagetheatrejobs/")

    time.sleep(1)

    driver.find_element_by_xpath("//*[contains(text(), 'New activity')]").click()
    driver.find_element_by_xpath("//*[contains(text(), 'See most recent posts first')]").find_element_by_xpath('..').click()
python selenium selenium-chromedriver
2个回答
1
投票

而不是这个:

driver.find_element_by_xpath("//*[contains(text(), 'New activity')]").click()
driver.find_element_by_xpath("//*[contains(text(), 'See most recent posts first')]").find_element_by_xpath('..').click()

通过 显式等待来做到这一点:

driver.maximize_window()
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.XPATH, "//*[contains(text(), 'New activity')]"))).click()
wait.until(EC.element_to_be_clickable((By.XPATH, "//*[contains(text(), 'See most recent posts first')]"))).click()

进口:

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

或者如果你只是想获取视觉坐标,你可以这样做:

wait = WebDriverWait(driver, 10)
new_activity_web_element = wait.until(EC.element_to_be_clickable((By.XPATH, "//*[contains(text(), 'New activity')]")))
y_relative_coord = new_activity_web_element.location['y']
x_absolute_coord = new_activity_web_element.location['x']

0
投票

迟到的答案,但也许有人会寻找它,所以:在这种情况下使用上下文单击可能会有所帮助。从技术上讲,它应该移动到元素的中心,然后执行我们所知的右键单击。这是通过分析右键单击后出现的上下文菜单的位置来直观地了解单击的确切位置的一种方法。

WebElement btnMostRecentPosts = driver
    .find_element_by_xpath("//*[contains(text(), 'See most recent posts first')]")
    .find_element_by_xpath('..');

new Actions(driver).contextClick(btnMostRecentPosts)
    .perform();
© www.soinside.com 2019 - 2024. All rights reserved.