gpt4 book ai didi

Python+Selenium,无法点击span包裹的 'button'

转载 作者:行者123 更新时间:2023-12-01 03:42:13 24 4
gpt4 key购买 nike

我是 Selenium 的新手。我尝试使用 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事件,我无法成功点击它。

我的上一个版本如下所示:

driver = webdriver.Firefox()
driver.get(newurl)
page_source = driver.page_source
soup = BeautifulSoup(page_source)
moreID = soup.find("span", class_=re.compile(r'.*\bmoreLink\b.*'))['class']
moreID = '.'.join(moreID[0:(len(moreID)+1)])
moreButton = 'span.' + moreID
button = driver.find_element_by_css_selector(moreButton)
button.click()
time.sleep(10)

但是,我不断收到如下错误消息:

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

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

最佳答案

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

当元素不在视口(viewport)中并且 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() 在单击之前访问该元素,如下所示:-

    driver.execute_script("arguments[0].scrollIntoView(true)", button)
    button.click()
  • 您可以尝试将 JavaScript::click()execute_script() 结合使用,但此 JavaScript::click() 失败测试的目的。首先,因为它不会生成所有事件,例如真正的单击(焦点、模糊、mousedown、mouseup...);其次,因为它不能保证真正的用户可以与元素交互。但要摆脱这个问题,您可以将其视为替代解决方案。

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

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

关于Python+Selenium,无法点击span包裹的 'button',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39399266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com