python - Selenium 按 ID 点击

标签 python selenium

我遵循了这里的代码:Selenium Python get_element by ID failing

但是还是不行

这是我的代码

from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

BLACKBERRY_UA = "Mozilla/5.0 (BlackBerry; U; BlackBerry 9900; en) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.1.0.346 Mobile Safari/534.11+"
opts = Options()
opts.add_argument("user-agent={0}".format(BLACKBERRY_UA))

root_url = 'http://www3.hkexnews.hk/listedco/listconews/advancedsearch/search_active_main.aspx'
ticker = '700'

driver = webdriver.Chrome(chrome_options=opts)
driver.get(root_url)

# 1 enter ticker
stock_code = WebDriverWait(driver, 5).until(ec.element_to_be_clickable((By.ID, "ct100_txt_stock_code")))
stock_code.click()
stock_code.send_keys(ticker)

#2 click on "Headline Category" radio button
button = WebDriverWait(driver, 5).until(ec.element_to_be_clickable((By.ID, "ct100_rbAfter2006")))
button.click()

#3 choose "Announcements and Notices" from drop down
driver.find_element_by_xpath("//select[@id='ct100_sel_tier_1']/option[text()='Announcements and Notices']").click()

# 4 click on "Search"
driver.find_element_by_xpath('//a[@href = \\"javascript: if (preprocessMainForm() == true )  document.forms[0].submit()"\\]').click()  # click on search buttom

我已经测试了这 4 个步骤中的每一个,但没有一个起作用。我也尝试过 By.NAME 但它仍然不起作用。我收到 TimeoutException。不确定 Selenium 是否找到了元素,为什么超时?

最佳答案

由于找不到元素而超时。如果您手动查看 html,您会发现 id 与您正在使用的不同。

例如,您有:

stock_code = WebDriverWait(driver, 5).until(ec.element_to_be_clickable((By.ID, "ct100_txt_stock_code")))

应该是:

stock_code = WebDriverWait(driver, 5).until(ec.element_to_be_clickable((By.ID, "ctl00_txt_stock_code")))

查看 ID 值。 ID 的“ctl100”部分是小写 L,而不是 1。检查其他内容,然后将 html ID 复制并粘贴到您的代码中。

这适用于前 3 个步骤,但对于第 4 步,请使用:

driver.find_element_by_xpath("/html//form[@id='aspnetForm']/table//a[@href='javascript: if (preprocessMainForm() == true )  document.forms[0].submit();']").click()  # click on search buttom

关于python - Selenium 按 ID 点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56570957/

相关文章:

python - 使用 boost::python::make_function 设置 __name__ 属性

Selenium:- 无法定位元素

php - 如何使用 facebook WebDriver 获取 AJAX 页面的当前 HTML 源代码?

c# - webdriver 模态窗口 click() 不工作

selenium - 如何使用 selenium java 从多选下拉列表中显示所选选项?

c# - 在 C# 中使用 Selenium RemoteWebDriver

python - 使用 read_csv() 创建的 DataFrame 给出了意外的 query() 结果

python - 为什么带有尾随冒号的 PYTHONPATH 将当前目录添加到 sys.path?

python - 将 pandas 中两个时间列之间的差异计算为不包括周末的新列,此时列可能包含 NaT

python - 如何用Python读取RINEX文件?