正在尝试使用selenium和python刮取此页

2024-04-24 18:42:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图用selenium/python来刮取这个页面/iframe,但是我不能在这个选中的表单中插入任何文本。你知道吗

link

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

有什么建议吗?你知道吗


Tags: namefromimporturlbydriverseleniumsleep
2条回答

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()

类名“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

相关问题 更多 >