【问题标题】:How to redirect page rendered with React to other page when clicking on button with Python in Selenium?在 Selenium 中单击 Python 按钮时,如何将使用 React 呈现的页面重定向到其他页面?
【发布时间】:2019-08-29 13:52:38
【问题描述】:

我目前正在尝试抓取页面的内容,比如说它叫做 https://example.com/home 。当我在该页面上的浏览器上导航时,我被重定向到此页面https://example.com/home/quiz,我需要单击一个按钮才能退出该页面并重新导航到https://example.com/home。我试图在我的 python 代码上重现它,如下所示:

try:
    url = "https://example.com/home"
    driver.get(url)
    # execute script to scroll down the page
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
    time.sleep(10)
 
    #this page prints https://example.com/home/quiz
    print(driver.current_url)

    #button which redirects to https://example.com/home
    button = driver.find_element_by_xpath("//*[@id='course-placeholder']/div/div[2]/div[3]/div[2]/a")
    print(button)
    # execute script to scroll down the page
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
    time.sleep(10)  

    #get current page
    #this page prints also https://example.com/home/quiz
    print(driver.current_url)

except Exception as e: 
    print(e)

这是使用 React.js 呈现的 https://example.com/home/quiz 页面的结构:

有谁知道为什么我在点击按钮后不能被重定向回https://example.com/home?我不知道发生了什么,任何帮助将不胜感激!提前致谢

【问题讨论】:

  • 你没有点击按钮,只是获取按钮元素。

标签: python reactjs selenium redirect web-scraping


【解决方案1】:

很可能,您忘记将click() 方法添加到您的按钮。否则,它可能与您的选择器有关。

 button = driver.find_element_by_xpath("//*[@id='course-placeholder']/div/div[2]/div[3]/div[2]/a")
 button.click()

如果上述解决方案没有解决您的问题,请尝试以下操作:

button = driver.find_element_by_css_selector("a.overlay-close")
button.click()

【讨论】:

  • 你不能打印button.click()...没什么。打印 button 将打印该特定元素的一些 ID 并且不可读。
猜你喜欢
  • 2023-03-08
  • 1970-01-01
  • 2021-11-23
  • 2016-01-24
  • 2020-07-28
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多