from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
global browser
browser= webdriver.Chrome()
browser.get("https://www.google.com")
wait = WebDriverWait(browser,45)
search = browser.find_element(By.NAME,"q")
search.send_keys("Amazon")
search.send_keys(Keys.RETURN)
wait.until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT,"amazon.in"))).click()
search = wait.until(EC.presence_of_element_located((By.ID,"twotabsearchtextbox")))
search.send_keys("PS5")
search.send_keys(Keys.RETURN)
wait.until(EC.presence_of_element_located((By.LINK_TEXT,"Sony PS5 PlayStation Console"))).click()
try:
add_to_cart_button = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="add-to-cart-button"]')))
add_to_cart_button.click()
except Exception as e:
print("Error:", e)
finally:
browser.quit()
time.sleep(2)
browser.quit()
'''我确实尝试过显式时间来搜索元素,因为它给出了定位元素的时间。我也开始使用 XPATH,但它没有任何作用。当涉及“添加到购物车”按钮时,一切都很顺利,但网络驱动程序找不到该元素。'''
你无法获取元素,因为线
wait.until(EC.presence_of_element_located((By.LINK_TEXT,"Sony PS5 PlayStation Console"))).click()
打开新选项卡。
Selenium
不会自动切换上下文,因此您应该在单击后将上下文切换到新选项卡。
window_handles = browser.window_handles
new_window_handle = window_handles[-1]
browser.switch_to.window(new_window_handle)
顺便说一句,您可以直接访问亚马逊链接,而不必在 Google 中搜索。