是否可以在此 Power BI 此处获取下拉菜单“MUNICIPIO”中的所有名称?
到目前为止,我已经成功点击了菜单。但只有部分选项出现在 htlm 代码中。
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.common.action_chains import ActionChains
cService = webdriver.ChromeService("chromedriver.exe")
driver = webdriver.Chrome(service = cService)
url = "https://app.powerbi.com/view r=eyJrIjoiYjQ1NTA2OTYtYTNkMi00ZTM4LWI2ODUtZjE0MTdhODg2OWU3IiwidCI6IjU2YzFlMmZiLTg3YzEtNGRlMC1hNmFjLWQwNTY2YzA4Y2U2NiJ9"
driver.get(url)
clickable = driver.find_element(By.CSS_SELECTOR, "div[aria-label='MUNICIPIO']")
ActionChains(driver).context_click(clickable).perform()
driver.find_element(By.CSS_SELECTOR, "div[class = 'pbi-menu-item-text-container'").click()
我的最终目标是在得到他们的名字后循环浏览菜单中的选项。
我的解决方案侧重于将 Keys.DOWN 发送到下拉菜单并读取突出显示的元素。它并不好也不完美,但它能完成工作。
curr_elem = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, '//div[@data-row-index=1]'))) curr_elem.send_keys(Keys.DOWN) elems = [] while len(elems) == 0 or elems[i-1] != curr_elem.text: elems.append(curr_elem.text) curr_elem.send_keys(Keys.DOWN) time.sleep(0.1) curr_elem = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, '//div[@class="slicerItemContainer setFocusRing"]'))) i += 1
time.sleep() 是必需的,否则 Selenium 读取元素文本的速度有时会比网站对向下键的反应更快。