在selenium-python中使用xpath查找元素文本NOt Working

时间:2017-01-25 11:54:46

标签: python-2.7 selenium xpath selenium-chromedriver

html looks like this我已经编写了这段代码来从网址中删除所有课程。为此,我试图使用xpath来计算课程数量。但它没有给我任何东西。我在哪里做错了?

import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait`

class FinalProject:

    def __init__(self,url= "https://www.class-central.com/subject/data-science"):`
        self.url = url
        base_url = 'https://www.class-central.com'
        self.error_flag = False
        self.driver = webdriver.Chrome(<path to chromedriver>)
        self.driver.get(self.url)
        sleep(2)
        self.count_course_and_scroll()

    def count_course_and_scroll(self):
        wait = WebDriverWait(self.driver, 30);
        ele = wait.until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, 'Not right now, thanks.')));
        ele.click()
        print "----------------------POP UP CLOSED---------------------"
        total_courses = self.driver.find_element_by_xpath("//span[@id='number-of-courses']")
        print total_courses
        print total_courses.text
        self.driver.close()

fp = FinalProject()

2 个答案:

答案 0 :(得分:0)

如果text不起作用,您可以尝试get_attribute

print total_courses.get_attribute('text')
#or
print total_courses.get_attribute('innerHTML')

答案 1 :(得分:0)

ele = wait.until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, 'Not right now, thanks.')));
ele.click()
print "----------------------POP UP CLOSED---------------------"
total_courses = self.driver.find_element_by_xpath("//span[@id='number-of-courses']")

在那段代码中,我怀疑两件事:

  1. 弹出窗口是否始终显示?
  2. number-of-courses的文字是否及时显示?
  3. 如果你不确定1.我会建议把它放在试试中

    大约2. - 等到该元素上出现一些文字

    try:
        ele = wait.until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, 'Not right now, thanks.')));
        ele.click()
    finally:
        total_courses = wait.until(EC.presence_of_element_located(By.XPATH, "//span[@id='number-of-courses' and text() != '']")
        print total_courses.text