我正在尝试自动化一个流程,我可以访问网站,将鼠标悬停在菜单导航栏上,然后单击下拉列表中的选项来访问该页面。
我正在使用 Selenium(使用 python)来实现此目的,并使用“https://www.shoppersstop.com/”来测试我的代码。
当我运行下面的代码时,网站会正确打开,但我得到一个空白下拉列表,这就是为什么当我尝试单击下拉列表中的任何选项时,我收到“找不到元素”错误。
我尝试使用相同的代码在 Amazon.In 网站中查看下拉菜单,并且它工作正常。我还尝试在操作之间添加 time.sleep() 但仍然不起作用。
以下错误消息: 消息:没有这样的元素:无法定位元素:{"method":"xpath","selector":"//a[text()='All Indian Wear']"} (会话信息:chrome=123.0.6312.107);有关此错误的文档,请访问:https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception
以下是我的代码:
from selenium import webdriver
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.action_chains import ActionChains
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
import pandas as pd
import requests
import time
import re
# Set Chrome options
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--user-agent=Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36")
# Initialize driver with Chrome options
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://www.shoppersstop.com/") # Open the website
driver.maximize_window() #Maximize window
try:
WebDriverWait(driver, 20).until(lambda driver: driver.execute_script('return document.readyState') == 'complete')
#time.sleep(10)
actions = ActionChains(driver)
women_category = driver.find_element(By.XPATH, "//html/body/main/header/nav/div[1]/div/ul[2]/li[4]/a")
actions.move_to_element(women_category) # Hover over the Women's category to reveal the dropdown
actions.perform()
#time.sleep(30)
indian_wear = driver.find_element(By.XPATH, "//a[text()='All Indian Wear']")
actions.move_to_element(indian_wear).perform().click()
#time.sleep(20)
except Exception as e:
print(e)
driver.quit() # Close the browser
上面已经提到了。
常规 Selenium 在该网站的某些部分被屏蔽,但 https://github.com/seleniumbase/SeleniumBase 成功通过:
pip install seleniumbase
,然后使用 python
运行以下命令:
from seleniumbase import SB
with SB(uc=True, test=True) as sb:
sb.driver.get("https://www.shoppersstop.com/")
sb.hover_and_click('a[title="WOMEN"]', "//a[text()='All Indian Wear']")
breakpoint()
在控制台中输入
c
并按 Enter
以从 Python breakpoint()
继续。
请注意,
SeleniumBase
会自动检测选择器,因此您可以对内置 SeleniumBase 方法使用 CSS 或 XPath。