首页 > 解决方案 > NoSuchElementException 之后如何继续

问题描述

我正在尝试使用 find_element_by_class_name("picture") 获取所有 href 但我在 NoSuchElementException 中卡住了一段时间并且硒卡住了

我添加了try/except,但它似乎不起作用

for link in url_list:
 try:
    Mydriver.get(link)
    product = Mydriver.find_elements_by_xpath("//a[@href]")
    for pr in product:
        if ("reseller.c-data.co.il" not in link):
            continue
        else:
            if (Mydriver.find_element_by_class_name("product-title")):
                product_link = pr.get_attribute("href")
                product_list.append(product_link)
                print(product_link)
except NoSuchElementException:
    print ("erron on url :", product_link)
    continue

我希望 selenium 将继续,代码将移至 url_list 中的下一个链接。但我得到的只是“ selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{“method”:“css selector”,“selector”:“.picture”}“

该怎么办 ?

标签: pythonpython-3.xseleniumexception

解决方案


鉴于您提供的代码,我认为您可以组合不同的过滤器并完全避免该问题。您正在寻找A具有 href 属性的标签...然后检查 href 是否包含“reseller.c-data.co.il”,然后搜索具有类名“product-title”的子元素。您可以使用 CSS 选择器完成所有这些操作

for link in url_list:
    Mydriver.get(link)
    for pr in Mydriver.find_elements_by_css_selector("a[href*='reseller.c-data.co.il'] .product-title"):
        product_link = pr.get_attribute("href")
        product_list.append(product_link)
        print(product_link)

您还可以使用 XPath: //a[contains(@href,'reseller.c-data.co.il')]//*[@class='product-title']。我更喜欢 CSS 选择器,因为它们更快,在不同的浏览器中得到更好的支持,而且语法更简单。

CSS 选择器参考

W3C 规范选择器概述
Selenium 技巧:CSS 选择器
驯服高级 CSS 选择器


推荐阅读