Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 无法将两个循环合并为一个以满足这两个要求_Python 3.x_Selenium Webdriver_Web Scraping_Web Crawler - Fatal编程技术网

Python 3.x 无法将两个循环合并为一个以满足这两个要求

Python 3.x 无法将两个循环合并为一个以满足这两个要求,python-3.x,selenium-webdriver,web-scraping,web-crawler,Python 3.x,Selenium Webdriver,Web Scraping,Web Crawler,当我的刮板跟随一些链接到达目标页面时,它发现有两种类型的元素需要处理。少数页面包含第一个模式,而其他页面包含第二个模式。我想在我的脚本中创建任何条件语句或类似try/except block的语句,这样它将尝试第一个语句,如果失败,它将尝试另一个语句。我不知道怎么做。希望有什么建议能让我来 for item in docs.find_elements_by_xpath("//div[contains(@class,'pv-top-card-section__information')]"):

当我的刮板跟随一些链接到达目标页面时,它发现有两种类型的元素需要处理。少数页面包含第一个模式,而其他页面包含第二个模式。我想在我的脚本中创建任何条件语句或类似try/except block的语句,这样它将尝试第一个语句,如果失败,它将尝试另一个语句。我不知道怎么做。希望有什么建议能让我来

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)

假设您使用的是Selenium,您可以将XPath存储在一个列表中,并在其中循环,直到找到匹配的XPath。比如:

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
,在这两种情况下,它都将尝试下一种模式-您可以围绕内部
项。通过xpath(项路径)查找元素
使用相同的
尝试..except
块来处理项目级别上未找到的异常,而不是移动到下一个元素路径。

那么您想将两个循环合并为1?对不起,你能说得更具体一点吗?如果你能在中编辑的话,我将不胜感激。谢谢zwer先生,为你提供了强大而有效的解决方案。这正是我所期待的。