Python+Selenium,无法单击span包装的“按钮”

2024-09-30 01:19:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉硒。每次刷新页面后,我都尝试使用selenium单击“更多”按钮来展开评论部分。在

网站是TripAdvisor。more按钮的逻辑是,只要你点击第一个more按钮,它就会自动为你展开所有的评论部分。换句话说,你只需要点击第一个“更多”按钮。在

所有按钮都有相似的类名。例如taLnk.hvrIE6.tr415411081.moreLink.ulBlueLinks。只有数字部分每次都会改变。在

整个元素如下所示:

<span class="taLnk hvrIE6 tr413756996 moreLink ulBlueLinks" onclick="          var options = {
      flow: 'CORE_COMBINED',
      pid: 39415,
      onSuccess: function() { ta.util.cookie.setPIDCookie(2247); ta.call('ta.servlet.Reviews.expandReviews', {type: 'dummy'}, ta.id('review_413756996'), 'review_413756996', '1', 2247);; window.location.hash = 'review_413756996'; }
    };
    ta.call('ta.registration.RegOverlay.show', {type: 'dummy'}, ta.id('review_413756996'), options);
    return false;
  ">
More&nbsp; </span>

我试过几种方法来按一下按钮。但由于它是一个由span包装的onclick事件,所以我无法成功地单击它。在

我的上一个版本是这样的:

^{pr2}$

但是,我一直收到这样的错误消息:

WebDriverException: Message: Element is not clickable at point (318.5, 7.100006103515625). Other element would receive the click....

你能告诉我怎么解决这个问题吗?任何帮助都将不胜感激!在


Tags: moretype评论call按钮reviewdummyoptions
2条回答

尝试使用^{}

from selenium.webdriver.common.action_chains import ActionChains
# Your existing code here
# Minus the `button.click()` line
ActionChains(driver).move_to_element(button).cli‌​ck().perform()

当我需要单击<div><span>元素而不是实际的按钮或链接时,我就使用了这种技术。在

WebDriverException: Message: Element is not clickable at point (318.5, 7.100006103515625). Other element would receive the click....

当元素不在视图端口中并且selenium由于其他覆盖元素而无法单击时,将发生此错误。在这种情况下,您应该尝试以下解决方案之一:-

  • 您可以尝试使用ActionChains在单击之前访问该元素,如下所示:

    from selenium.webdriver.common.action_chains import ActionChains
    
    button = driver.find_element_by_css_selector(moreButton)
    
    ActionChains(button).move_to_element(element).click().perform()
    
  • 您可以尝试使用execute_script()访问该元素,然后单击as:-

    driver.execute_script("arguments[0].scrollIntoView(true)", button)
    button.click()
    
  • 您可以尝试将JavaScript::click()execute_script()一起使用,但这JavaScript::click()会破坏测试的目的。第一个原因是它不能像真正的单击那样生成所有事件(focus、blur、mousedown、mouseup…),第二个原因是它不能保证真正的用户可以与元素交互。但是为了摆脱这个问题,你可以把它当作一个替代方案。在

    driver.execute_script("arguments[0].click()", button)
    

注意:-在使用这些选项之前,请确保您尝试使用正确的定位器与正确的元素进行交互,否则,WebElement.click()在使用WebDriverWait可见并可单击元素之后,才能正常工作。在

相关问题 更多 >

    热门问题