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
PATH = ("C:/Users/User/Desktop/msedgedriver.exe")
driver = webdriver.Edge(PATH)
driver.get("https://www.google.com.tw/")
WaitForPageOpen = WebDriverWait(driver, 10).until(
EC.presence_of_element_located(
(By.NAME, "q"))
)
Google_Search = driver.find_element(By.NAME, "q")
time.sleep(1)
Google_Search.click()
Search1 = driver.find_element(By.NAME, "q")
time.sleep(1)
Search1.send_keys("shopee")
Search1.send_keys(Keys.RETURN)
WaitForPageOpen2 = WebDriverWait(driver, 10).until(
EC.presence_of_element_located(
(By.ID, "center_col"))
)
Click2 = driver.find_element(
By.CLASS_NAME, "VuuXrf")
Click2.click()
time.sleep(2)
WaitForPageOpen3 = WebDriverWait(driver, 10).until(
EC.presence_of_element_located(
(By.ID, "main"))
)
wait_for_ad = WebDriverWait(driver, 30).until(
EC.presence_of_element_located(
(By.CLASS_NAME, "home-popup__close-button")
)
)
close_ad_button = driver.find_element(
By.CLASS_NAME, "home-popup__close-button")
close_ad_button.click()
改用 ActionChains 試試?
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
...略...
action = ActionChains(driver)
action.pause(5).perform()
action.click(on_element=driver.find_element(By.XPATH,'/html/body/div[1]/div/header/div[2]/div/a')).perform()
可以從開發者面板中看到,它是在中間廣告區用一個超連結包起來,對它來說使用者只有兩條路:
所以換個思路,你要點的不是那個(x),而是要點廣告框以外的地方。
這邊利用了 ActionChains 模擬滑鼠點擊 左上角的蝦皮購物logo連結,我這邊測試過是ok的。
註: 我用 Selenium+Chrome 測試,換到 Edge 或許語法略有不同,但邏輯應該是一樣的。
最簡單就是refresh
但是樓上的才是終極辦法!!!
可以參考
https://selenium-python.readthedocs.io/api.html#selenium.common.exceptions.WebDriverException
driver.get("https://shopee.tw/")
driver.refresh()
sleep(2)
driver.refresh()
sleep(2)
driver.refresh()