簡體   English   中英

無法使用 python selenium webdriver 切換到新頁面?

[英]can not switch to a new page using 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 中是否還有其他方法可以這樣做並切換到新的 windows?

問題是您的等待條件不正確。 單擊提交 window 更改后,它不會打開新的 window。

更好的選擇是等待帶有.csv 文件的頁面加載然后下載。

我的解決方案:

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


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()

WebDriverWait(driver, 60).until(EC.presence_of_element_located((By.XPATH, "//a[contains(text(), 'Download CSV')]")))
driver.find_element(By.XPATH, "//a[contains(text(), 'Download CSV')]").click()

如您所見,我正在等到找到“下載CSV”,然后按下它。

另請注意,下載目錄將是 chrome 默認目錄,但您可以通過添加以下內容進行更改:

options.add_argument("download.default_directory=path")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM