所以我有点卡住了!我正在尝试从“所有评论”下拉菜单中选择一个项目,但是它不会像我可以选择每个元素然后单击它的位置那样进行交互。
相反,行为就像一个元素,在其标签更改时显示不同的结果。有谁知道我该如何从菜单中选择一个元素?
例如,使菜单从下拉菜单中选择“ Google”标签。
答案 0 :(得分:1)
出现此特定网页元素时,其中许多元素不仅仅存在于DOM内容中,您应该使用WebDriverWait方法来等待直到找到特定元素。
例如,让我们根据您的要求选择“ Google”:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("the google link here, it's too big to paste it")
#Waiting until dropdown is visible , there are two dropdowns, taking the first one
menu = WebDriverWait(driver,5).until(EC.visibility_of_element_located((By.XPATH, "
(//div[@class='cYrDcjyGO77__container'])[1]")))
menu.click()
#Waiting untill menu items is visible then selecting the second element - Google
item = WebDriverWait(driver,5).until(EC.visibility_of_element_located((By.XPATH, "
(//div[@role='menuitem'])[2]")))
item.click()
答案 1 :(得分:1)
您可以做的是找到您的下拉列表,然后列出所有选项并选择您的选项。 这是我的做法
el = driver.find_element_by_id("dropdown_id")
for option in el.find_elements_by_tag_name('option'):
if "GB" in option.text:
option.click() # select() in earlier versions of webdriver
break
我正在选择状态为“ GB”的下拉菜单。
答案 2 :(得分:1)
引入WebDriverWait
()和element_to_be_clickable
(),然后单击All reviews
div元素以打开下拉菜单,然后基于文本选择项目。
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver=webdriver.Chrome()
driver.get("https://www.google.com/maps/place/Hilton+London+Bankside/@51.5056536,-0.1033145,17z/data=!3m1!4b1!4m10!3m9!1s0x487604af6af74cc7:0x6c4cb3cbe03e95bf!5m2!4m1!1i2!8m2!3d51.5056536!4d-0.1011258!9m1!1b1")
#Dropdown text provide here
selectItem='Agoda'
#First click on the All reviews element to open up the dorpdown element
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"div[aria-label='All reviews']"))).click()
#Select item from menu dropdown by text
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//div[@role='menuitem']//div[text()='"+ selectItem +"']"))).click()
浏览器快照:执行后