2017-06-11 75 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