2017-02-21 37 views
0

我在Python3中使用硒,我正在努力填写调查问卷。在本调查问卷中,我将遍历所有问题并回答问题。我的问题是弄清楚我正在处理的是什么类型的问题,无论问题是多选还是文本问题。我想这样做的是类似以下内容:有没有办法比较XPath来确定正在查看的元素类型?

while questionsLeft: 
    if currentQuestion == textQuestion: 
     answerAsTextQuestion() 
    elif currentQuestion == multChoice: 
     answerAsMultChoice() 

但我在实施这一点,因为我不知道如何验证,如果我看的元素是文本框或麻烦多选题。以下是分别用于文本问题和多选题的HTML。

我到目前为止是以下内容,都没有条件通过,所以它每次都会直接进入下一部分。

self.set_filter("unanswered") 

    all_sections = AssessmentSection(self.driver).get_all_section_names() 
    print(all_sections) 

     i = 1 
     self.driver.implicitly_wait(3) 

     for element in self.driver.find_elements_by_xpath('(//div[@bo-if])'): 
      self.driver.implicitly_wait(3) 
      print("in for loop at " + all_sections[j]) 
      if element.get_attribute("bo.if") == "questionResponse.question.type === 'TextQuestion'": 
       print("found text question") 
       self.driver.find_element_by_xpath('.//pre[@class="textareaClone"]//div').send_keys(XpathData.test_string) 
       self.driver.find_element_by_xpath('.//pre[@class="textareaClone"]//div').send_keys(Keys.TAB) 
       i += 1 
      elif element.get_attribute(
        "bo.if") == "questionResponse.question.type === 'SingleSelectQuestion' || questionResponse.question.type === 'PolarQuestion'": 
       print("found choice question") 
       self.driver.find_element_by_xpath(
        './/*[@id="ng-app"]/body/div[1]/div[3]/div/div/div[2]/div[3]/div[' + str(
         i) + ']/div/div/div/div[2]/div[1]/label').click() 
       i += 1 


     Wait(self.driver, Wait.timeout).until(EC.visibility_of_element_located((By.XPATH, '//div[contains(text(), \'' + all_sections[j] + '\')]'))) 
     self.driver.find_element_by_xpath('//div[contains(text(), \'' + all_sections[j] + '\')]').click() 
     j += 1 
     print(j) 
+1

你能分享两个元素的HTML样本吗?还分享'questionsLeftInQuestionnaire()'的代码' – Andersson

+0

为元素添加了HTML。截至目前questionsLeftInQuestionnaire()有一个遍历所有问题的循环,当迭代器没有任何剩余的问题可供引用时抛出异常。 – TheOneTrueSign

回答

1

当你的questionsLeftInQuestionnaire()逻辑是隐藏的代码下面是简化版本,你可以实现:

for element in driver.find_elements_by_xpath('//div[@bo-if]'): 
    if element.get_attribute("bo.if") == "questionResponse.question.type === 'TextQuestion'": 
     answerAsTextQuestion() 
    elif element.get_attribute("bo.if") == "questionResponse.question.type === 'SingleSelectQuestion' || questionResponse.question.type === 'PolarQuestion'": 
     answerAsMultChoice() 

如果属性bo-if的值对每个元素的不同,你可以尝试使用if "||" in element.get_attribute("bo.if")条件

+0

我添加了我的完整代码,我相信我遇到的问题不是解决任何问题类型(multChoice和Text) – TheOneTrueSign

+0

代码的输出是什么?哪条线似乎是你的问题的原因?你可以分享页面的URL吗?或者它是保密的? – Andersson

+0

用我现在的代码没有错误。基于代码在每个部分中运行的逻辑,认为没有更多的问题需要回答。也就是说,它从第1部分开始,没有留下任何问题要回答(这是错误的),并转到下一部分并继续到最后一部分。恐怕'URL'是保密的,我的道歉。 – TheOneTrueSign

相关问题