2014-09-11 26 views
0

所以基本上我在以下網頁中使用selenium:http://www.registrar.ucla.edu/schedule/catalog.aspx?sa=APPLING&funsel=3。我創建了一個驅動程序,我正在尋找符合某些特定條件的粗體文本。下面是搜索的文字加粗,並找到了匹配我的代碼部分:使用Selenium Python查找下一個標籤

# Finds all bold matches which contain the class title 
    bold_matches = driver.find_elements_by_class_name('bold') 
    class_title = '' 
    class_description = '' 
    for bold_match in bold_matches: 
     # If the class title matches, we set our class title 
     if bold_match.text[:bold_match.text.find('.')] == class_number: 
      class_title = bold_match.text 

您不必擔心代碼之外的事實太多,一旦我們發現有一個匹配的文本元素,我們將文本設置爲類標題。

使用Selenium需要幫助的是獲取匹配文本的下一個標籤。所以我需要匹配bold_match之後的標籤。下一個標籤包含設置class_description文字的文字。

我看了一下類似的問題,但他們都引用匹配id與xpath。這個網頁的問題是粗體文本標籤和它後面的標籤不包含任何id。

+0

該標籤是否需要孩子或'bold_match'元素的兄弟?抱歉,我無法從您的描述中理解。 – 2014-09-11 09:28:04

+0

我需要bold_match元素的兄弟。我實際上發現了一個駭人的做法,我會把它作爲我的回答。如果你知道一個更好的方法來做到這一點,讓我知道。 – user2548635 2014-09-11 13:48:32

回答

0

我發現了一種駭人的方式去做我需要的東西。下面是我的代碼:

# Finds all bold matches which contain the class title 
bold_matches = driver.find_elements_by_class_name('bold') 
class_title = '' 
class_description = '' 
for bold_match in bold_matches: 
    # If the class title matches, we set our class title 
    if bold_match.text[:bold_match.text.find('.')] == class_number: 
     class_title = bold_match.text 

     # We find the class description from the class title 
     all_elements = driver.find_elements_by_xpath('//*') 
     matching_index = all_elements.index(bold_match) + 2 
     class_description = all_elements[matching_index].text 

我發現了什麼是我可以找到我目前在a ll_elements列表匹配,然後找到一個相應的指數,以獲得class_description元素的索引。

+1

這將工作certianly,但你有沒有考慮使用'以下兄弟'軸? 'bold_match.find_element_by_xpath(「./ following-sibling :: tag_of_the_element_you_need」)' – 2014-09-12 08:39:33

+1

@MarkRowlands感謝您的回答。我不知道我們可以在任何webdriver元素上使用'find_element_by_xpath()'方法。 – user2548635 2014-09-12 17:55:40

相關問題