我遵循了这里的代码: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/