2017-01-25 57 views
0

html looks like this我已經編寫了這段代碼來清除url中的所有課程。爲此,我試圖使用xpath來計算課程數量。但它不給我任何東西。我在哪裏做錯了?在selenium-python中使用xpath查找元素文本NOt工作

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()

+0

請分享你工作的HTML代碼。 – Jose

+1

你有什麼錯誤嗎? – Guy

+0

@Jose我分享了html的截圖。我不知道我應該如何分享完整的。 –

回答

0

如果text不工作,你可以嘗試get_attribute

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

'print total_courses.get_attribute('innerHTML')'給了我結果,但是'print total_courses.get_attribute('text')'給出了NOne作爲輸出。爲什麼這樣?爲什麼'文本'不工作? –

+0

@python_user我不知道。它爲我工作。 – Guy

+0

@python_user也許你可以提取父文本'total_courses = self.driver.find_element_by_xpath(「// span [span [@ id ='number-of-courses']]」)print total_courses.text'。它會給你'187課程可用' – Guy

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']") 

在塔t片的代碼,我懷疑2件事:

  1. 彈出窗口總是出現嗎?
  2. number-of-courses的文字是否及時顯示?

如果你不能確定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 
+1

'嘗試'/'catch'?...你確定嗎? :)這絕對不是一個'Python'代碼。 https://docs.python.org/2.7/tutorial/errors.html#handling-exceptions – Andersson

+0

謝謝,我顯然不熟悉python。但這個想法仍然是一樣的。 –

相關問題