![](/img/trans.png)
[英]Selenium : I am able to open a new tab with Selenium but cannot make any action on this tab
[英]Python Selenium Why can't I perform any action after opening a new tab and closing the first tab with Selenium?
我試圖通過搜索特定產品、轉到產品頁面並獲取價格來從網站中提取價格數據。 但是,為了進入產品頁面,我似乎需要打開一個新標簽。 當我關閉舊選項卡時,我似乎無法執行任何其他操作或在新頁面上查找元素。
這是我的代碼:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.action_chains import ActionChains
import time
s = Service("C:\Program Files (x86)\chromedriver.exe")
driver = webdriver.Chrome(service=s)
driver.get("https://www.mcmaster.com/")
driver.maximize_window()
search = driver.find_element(By.ID, "SrchEntryWebPart_InpBox")
search.send_keys("91251A431") # search for part number
search.send_keys(Keys.RETURN)
try:
part = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, 'a[data-mcm-partnbr="91251A431"]'))
)
print(part.text)
ActionChains(driver) \
.key_down(Keys.CONTROL) \
.click(part) \
.key_up(Keys.CONTROL) \
.perform()
driver.close()
element = driver.find_element(By.CLASS_NAME, "PrceTxt")
print(element.text)
except:
print("Can't find price")
driver.quit()
在此示例的頁面上,我想打印出每包 10 個 8.59 美元。但是,似乎無論我在 driver.close() 之后放置什么代碼,都會執行 except 子句。 我很確定我的語法和元素名稱是正確的,但也許我缺少一些東西? 即使關閉舊標簽,我還需要選擇新標簽嗎?
在關閉舊選項卡之前嘗試切換窗口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.