【问题标题】:Selenium: select by 'option selected value', which isn't present when it's the defaultSelenium:通过'option selected value'选择,默认时不存在
【发布时间】:2020-01-24 15:22:49
【问题描述】:

我正在尝试从herehere 两个页面中抓取“活动”文本框。

我写了代码的基础:

options = Options()
options.binary_location=r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
options.add_experimental_option('excludeSwitches', ['enable-logging'])
#options.add_argument("--headless")
driver = webdriver.Chrome(options=options,executable_path='/mnt/c/Users/kela/Desktop/selenium/chromedriver.exe


url = 'http://www.uwm.edu.pl/biochemia/biopep/peptide_data_page1.php?zm_ID=' + str(i) #where str(i) is either 2500 or 2700 in this example
driver.get(url)
header = driver.find_element_by_css_selector('[name="activity"]')
children = header.find_elements_by_xpath(".//*")

我有两个问题:

  1. 我只需要拉出“选项选定值”的活动项,我不希望所有活动都返回。
  2. 但是如果选项是列表中的第一项,例如此处显示的活动为“aami”的页面之一; “选定值”不是一个选项,因为它是默认值。

所以我一直在寻找一两行代码,我可以添加到我的脚本中来提取:

neuropeptide | ne
alpha-amylase inhibitor | aami

来自这两个网页,如果有人可以提供帮助的话。

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    使用Select 类并获取first_selected_option。你需要诱导WebDriverWaitpresence_of_element_located

    i=2700
    url = 'http://www.uwm.edu.pl/biochemia/biopep/peptide_data_page1.php?zm_ID=' + str(i) #where str(i) is either 2500 or 2700 in this example
    driver.get(url)
    element=WebDriverWait(driver,20).until(EC.presence_of_element_located((By.NAME,"activity")))
    select=Select(element)
    print(select.first_selected_option.text)
    

    输出:

    neuropeptide    |    ne
    

    如果您将值更改为2500,您将获得alpha-amylase inhibitor | aami

    导入以下代码来执行上面的代码。

    from selenium.webdriver.support.select import Select
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium import webdriver
    

    【讨论】:

      【解决方案2】:

      您应该检查选项元素的属性。 如果任何选项中有“选定”属性,请获取它。 如果 'selected' 属性不在任何选项中,则只获取第一个选项。

      我已经使用 BeautifulSoup 实现了查找属性。您还可以通过执行 Javascript 代码来实现 Selenium。示例here

      我的代码:

      from selenium import webdriver
      from bs4 import BeautifulSoup
      
      driver = webdriver.Firefox()
      url = 'http://www.uwm.edu.pl/biochemia/biopep/peptide_data_page1.php?zm_ID=2500'
      
      driver.get(url)
      
      header = driver.find_element_by_css_selector('[name="activity"]')
      soup = BeautifulSoup(header.get_attribute("innerHTML"), 'html.parser')
      
      options = soup.find_all('option')
      for option in options:
          if 'selected' in option.attrs:
              print(option.text)
              break
      else:
          print(options[0].text.strip())
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-22
        • 2015-06-10
        • 1970-01-01
        • 1970-01-01
        • 2020-02-12
        相关资源
        最近更新 更多