python - Selenium 下拉按钮的问题
问题描述
我在选择下拉按钮然后选择其他选项来更改网页时遇到了一些问题。我在 Python 中使用 Selenium 来提取这些数据。网址是 https://www.transfermarkt.com/premierleague/startseite/wettbewerb/GB1/plus/?saison_id=2019
到目前为止的代码:
driver = webdriver.Chrome('C:/Users/bzholle/chromedriver.exe')
driver.get('https://www.transfermarkt.com/premierleague/startseite/wettbewerb/GB1/plus/?saison_id=2019')
#click out of iframe pop-up window
driver.switch_to.frame(driver.find_element_by_css_selector('iframe[title="SP Consent Message"]'))
accept_button = driver.find_element_by_xpath("//button[@title='ACCEPT ALL']")
accept_button.click()
driver.find_element_by_id("choosen-country").click()
我不断收到:NoSuchElementException:消息:没有这样的元素:无法找到元素
在 HTML 代码中,国家列表在单击下拉箭头之前不会出现;但是我无法点击按钮。有人有什么建议吗?
解决方案
这里有两个问题:
- 按下接受按钮后,您需要添加线
driver.switch_to.default_content()
以切换回iframe
- 您尝试识别的元素位于
shadow root
. 我知道识别这样一个元素的唯一方法是有点hacky,它涉及执行javascript来获取影子根,然后在影子根中找到元素。如果我使用此代码,则可以单击该元素:
driver = webdriver.Chrome('C:/Users/bzholle/chromedriver.exe')
driver.get('https://www.transfermarkt.com/premierleague/startseite/wettbewerb/GB1/plus/?saison_id=2019')
#click out of iframe pop-up window
driver.switch_to.frame(driver.find_element_by_css_selector('iframe[title="SP Consent Message"]'))
accept_button = driver.find_element_by_xpath("//button[@title='ACCEPT ALL']")
accept_button.click()
driver.switch_to.default_content()
shadow_section = driver.execute_script('''return document.querySelector("tm-quick-select-bar").shadowRoot''')
shadow_section.find_element_by_id("choosen-country").click()