2015-03-31 43 views
1

如何使用預期條件檢查HTML中是否存在br標記。這是HTML代碼:使用硒的預期條件

<br> 
<a href="member.php?u=12455" rel="nofollow">Smatta</a> 
<a>, </a> 
<a href="member.php?u=14305" rel="nofollow">Nyunyu</a> 
<a>, </a> 
<a href="member.php?u=20892" rel="nofollow">moyo</a> 
<a>, </a> 
<a href="member.php?u=21040" rel="nofollow">Masikini_Jeuri</a> 
<a>, </a> 
<a href="member.php?u=27429" rel="nofollow">Job K</a> 
<a>, </a> 
<a href="member.php?u=38124" rel="nofollow">Adoe</a> 
<a>, </a> 
<a href="member.php?u=39196" rel="nofollow">enhe</a> 
<a></a> 

這是我的代碼。

wait = WebDriverWait(browser, 10) 
wait.until(EC.visibility_of_element_located((By.XPATH, '//<br>'))) 

完整代碼。

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

browser = webdriver.PhantomJS() 
browser.maximize_window() 
browser.get("http://www.jamiiforums.com/kenyan-news/225589-kenyan-and-tanzanian-surburbs.html") 

username = browser.find_element_by_id("navbar_username") 
password = browser.find_element_by_name("vb_login_password_hint") 

username.send_keys("MarioP") 
password.send_keys("codeswitching") 

browser.find_element_by_class_name("loginbutton").click() 

wait = WebDriverWait(browser, 20) 
wait.until(EC.visibility_of_element_located((By.XPATH, '//h2[contains(., "Redirecting")]'))) 
wait.until(EC.title_contains('Kenyan & Tanzanian')) 
wait.until(EC.visibility_of_element_located((By.ID, 'postlist'))) 

browser.find_element_by_xpath('//div[@class="vbseo_liked"]/a[contains(@onclick, "return vbseoui.others_click(this)")]') 
browser.find_element_by_class_name("vbseo_liked").click() 

wait.until(EC.visibility_of_element_located((By.TAG_NAME, 'br'))) 
print (browser.page_source) 

print 'success!!' 
browser.close() 

我這樣做的原因是因爲br標籤只出現在鏈接被點擊後。我試圖在點擊操作後獲取頁面源代碼,但它在點擊操作之前給了我頁面源代碼。我想在獲取頁面源代碼之前檢查br標籤的存在。

這是打印出的錯誤。

文件 「sele.py」,第29行,在 wait.until(EC.visibility_of_element_located((By.TAG_NAME, 'BR')))

回答

1

這只是你的XPath表達式不正確,應該是:

//br 

或者,您可以使用 「標籤名」 定位:

wait.until(EC.visibility_of_element_located((By.TAG_NAME, 'br'))) 

作爲一個說明,我不確定你的意圖是什麼,但我從來沒有見過某個人會依賴在測試自動化或網頁抓取中存在br標記的情況。這並不一定意味着你做錯了什麼,但要確保有一個堅實的理由。

+0

感謝您的回覆。我這樣做的原因是因爲br標籤只在鏈接被點擊後纔出現。我試圖在點擊操作後獲取頁面源代碼,但它在點擊操作之前給了我頁面源代碼。我想在獲取頁面源代碼之前檢查br標籤的存在。我編輯了問題以包含我的代碼。 – user3078335 2015-03-31 14:40:35

+1

@ user3078335好的,謝謝,如果你使用'presence_of_element_located'而不是'visibility_of_element_located'呢? – alecxe 2015-03-31 14:50:16

+0

哦,好吧。我會嘗試。 – user3078335 2015-03-31 14:52:06