首页 > 解决方案 > 无法使用 python selenium webdriver 切换到新页面?

问题描述

我需要抓取网站的 CSV 结果(https://requestmap.webperf.tools/)。但我不能。

这是我需要做的过程:

1-加载网站(https://requestmap.webperf.tools/

2- 输入一个新网站作为输入(例如https://stackoverflow.com/

3-点击提交

4-在提交后打开的新页面中,下载页面末尾的csv文件

但我认为驱动程序具有主页并且不会切换到新页面。这就是我无法下载 CSV 文件的原因。

你能告诉我怎么做吗?这是我的代码:

options = webdriver.ChromeOptions()
options.add_argument('-headless')
options.add_argument('-no-sandbox')
options.add_argument('-disable-dev-shm-usage')
driver = webdriver.Chrome('chromedriver',options=options)
driver.get("https://requestmap.webperf.tools/")


driver.find_element_by_id("url").send_keys("https://stackoverflow.com/")
driver.find_element_by_id("submitter").click()

我已经测试了不同的方法来解决我的问题:首先:我从这里得到了这段代码:但它不起作用。

window_after = driver.window_handles[1]                           
driver.switch_to.window(window_after)

我也尝试过thisthis,但它们效果不佳。

# wait to make sure there are two windows open
# it is not working
WebDriverWait(driver, 30).until(lambda d: len(d.window_handles) == 2)

# switch windows
# it is not working
driver.switch_to_window(driver.window_handles[1])

content = driver.page_source
soup = BeautifulSoup(content)
driver.find_elements_by_name("Download CSV")

那么我怎样才能解决这个问题呢?

python中还有其他方法可以这样做并切换到新窗口吗?

标签: pythonseleniumselenium-webdriverurlpython-requests

解决方案


推荐阅读