2017-06-11 71 views
0

我的刮板在跟隨某些鏈接到達目標頁面時,發現有兩種類型的元素需要處理。幾頁包含第一個模式,而另一頁包含第二個模式。我想在腳本中創建任何條件語句或類似try/except塊的內容,以便在第一個腳本中嘗試,如果失敗,它將爲另一個腳本嘗試。我無法知道如何做到這一點。希望有任何建議我會到這裏。無法將兩個循環合併爲一個以滿足這兩個要求

for item in docs.find_elements_by_xpath("//div[contains(@class,'pv-top-card-section__information')]"): 
    name = item.find_element_by_xpath(".//h1[contains(@class,'pv-top-card-section__name')]") 
    print(name.text) 

for item in docs.find_elements_by_xpath("//div[contains(@class,'org-top-card-module__details')]"): 
    name = item.find_element_by_xpath(".//h1[@title]") 
    print(name.text) 
+0

所以你想將兩個循環合併爲1?對不起,你能更具體些嗎? –

+0

如果您可以編輯該文件,我們將不勝感激。 –

回答

1

假設你使用Selenium,你可以將你的xpaths存儲在一個列表中,並循環遍歷它們直到找到匹配。喜歡的東西:

search_paths = [ 
    ("//div[contains(@class,'pv-top-card-section__information')]", 
    ".//h1[contains(@class,'pv-top-card-section__name')]"), 
    ("//div[contains(@class,'org-top-card-module__details')]", 
    ".//h1[@title]"), 
    # etc. 
] 

# your init code 

for elements_path, item_path in search_paths: 
    try: 
     for item in docs.find_elements_by_xpath(elements_path): 
      name = item.find_element_by_xpath(item_path) 
      print(name.text) 
     break # all passed, you can remove the break to try all patterns 
    except selenium.common.exceptions.NoSuchElementException: # be sure to import it 
     pass # let it continue with the next pair of paths from the search_paths 

此外,這將捕獲NoSuchElementException兩個元素路徑,並在它的項目的路徑,在這兩種情況下,它會嘗試下一個模式 - 你可以圍繞內item.find_element_by_xpath(item_path)具有相同try..except塊來處理項目級未發現的異常,而不是移動到下一個元素路徑。

+0

感謝sir zwer,爲您提供強大有效的解決方案。這正是我所期望的。 – SIM