代码之家  ›  专栏  ›  技术社区  ›  jason

硒按ID单击

  •  0
  • jason  · 技术社区  · 5 年前

    我遵循了这里的代码: 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 . 不确定硒是否找到元素,为什么超时?

    1 回复  |  直到 5 年前
        1
  •  2
  •   RKelley    5 年前

    因为找不到元素,所以已经超时了。如果您手动查看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