如何搜索,向下箭头,然后按Selenium键

时间:2018-12-08 16:44:11

标签: python selenium selenium-webdriver autosuggest webdriverwait

我正在尝试搜索公司,向下箭头并在inhersight.com上单击Enter

我有以下代码,但似乎不起作用:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver.get("https://www.inhersight.com/companies")
elem = driver.find_element_by_class_name("open-search.small-hide.margin-right-20.icon-36.icon-search.reverse.cursor-pointer").click()
elem.send_keys("Apple")
elem.send_keys(Keys.ARROW_DOWN)

它似乎无法通过类名找到和查找元素。我已经尝试了很多东西,但是仍然无法正常工作……我迷路了

2 个答案:

答案 0 :(得分:0)

您可以避免选择,因为公司名称将成为URL中查询字符串的一部分,并用“-”代替空格,并使用小写字母。因此,您可以将.get指向此格式的URL。如果找不到公司,则可以添加一些处理。

from selenium import webdriver
company = 'Apple Federal Credit Union' # 'apple'
base = 'https://www.inhersight.com/company/' 
url = base + company.replace(' ', '-').lower()

d = webdriver.Chrome()
d.get(url)

#other stuff including handling of company not found (this text appears on the page so not hard)
#d.quit()

答案 1 :(得分:-1)

搜索公司并在inhersight.com上单击Enter ,而不是因为元素是自动建议,因此需要代替arrow down诱使 WebDriverWait 使所需的元素可点击,您可以使用以下解决方案:

  • 代码块:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.wait import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    options = Options()
    options.add_argument('start-maximized')
    options.add_argument('disable-infobars')
    options.add_argument('--disable-extensions')
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
    driver.get("https://www.inhersight.com/companies")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".open-search.small-hide.margin-right-20.icon-36.icon-search.reverse.cursor-pointer"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@placeholder='Search women-rated companies']"))).send_keys("Apple")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//li[contains(@class,'select2-highlighted')]/div[@class='select2-result-label']/div[@class='weight-medium']"))).click()