我正在尝试使用selenium / python抓取此页面/ iframe,但无法以此所选形式插入任何文本。
from selenium import webdriver
from time import sleep
driver = webdriver.Firefox()
url = 'http://web.transparencia.pe.gov.br/despesas/despesa-geral/'
driver.get(url)
sleep(10)
driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))
el = driver.find_element_by_xpath("//*[@id='html_selectug']")
el.click()
当我尝试获取列表框时:
el_cl = el.find_element_by_class_name('chzn-select')
el_cl.click()
引发异常
selenium.common.exceptions.ElementNotInteractableException: Message: Element <select class="chzn-select"> could not be scrolled into view
任何提示?
答案 0 :(得分:0)
类名“ chzn-select”不是您要单击的列表的正确类(屏幕快照中指定的那个)。
您可以尝试获取所有选项,然后按如下所示单击特定选项
AllOptions = driver.find_elements_by_xpath("//*[@id='html_selectug']/select/option")
for option in AllOptions:
if(option.get_attribute("value")=="option text you want to click")
option.click()
break
答案 1 :(得分:0)
Amith YR给了我一个很好的线索。这些选项处于不显示状态(如果要检查元素,则可以看到灰色代码)。我必须使用js代码使它们活跃。
from selenium import webdriver
from time import sleep
driver = webdriver.Firefox()
url = 'http://web.transparencia.pe.gov.br/despesas/despesa-geral/'
driver.get(url)
sleep(10)
# activate the options
js = "document.getElementById('iframe').contentWindow.document.getElementsByClassName('chzn-select')" \
"[1].style.display = 'inline';"
driver.execute_script(js)
# now, I'm able to grab the listbox options
driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))
options = driver.find_elements_by_xpath("//*[@id='html_selectug']/select/option")
options[4].click()