【问题标题】:how to continue after NoSuchElementExceptionNoSuchElementException 之后如何继续
【发布时间】:2019-09-12 18:12:14
【问题描述】:

我正在尝试使用 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”}“

怎么办?

【问题讨论】:

  • NSEE 错误发生在哪里?在我看来,如果在定义 product_link 之前发生 NSEE 错误,则错误可能出现在打印链接上,因此您永远不会点击 continue 语句。
  • 尝试将 if (Mydriver.find_element_by_class_name("product-title")) 更改为 if (Mydriver.find_elements_by_class_name("product-title") > 0) 请注意 elements 中的 s
  • 我的预感是你的 try & catch 放错了地方,但很难用那个错误信息来判断,因为它似乎与你的代码 sn-p 不匹配。 .picture 的选择器来自哪里?
  • @DMart - 那么在哪里放置 try/except ?当 selenium 到达 url [link] (facebook.com/ComputerCDATA) 时发生错误
  • @DvirYadae 是这个用例中的if ("reseller.c-data.co.il" not in link): 吗?你想通过它做什么?

标签: python python-3.x selenium exception


【解决方案1】:

鉴于您提供的代码,我认为您可以组合不同的过滤器并完全避免该问题。您正在寻找带有 href 属性的 A 标记...然后检查 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 spec Selectors Overview
Selenium Tips: CSS Selectors
Taming Advanced CSS Selectors

【讨论】:

  • 不 - 没有帮助。我仍然收到错误:elenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{“method”:“css selector”,“selector”:“.picture”}(会话信息:chrome = 76.0 .3809.132)
  • @Dev - 我已经尝试过你写的 - 它没有帮助。我仍然收到该错误:“selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{“method”:“css selector”,“selector”:“.picture”}(会话信息: 铬=76.0.3809.132)"
  • 我的代码中没有任何内容将 .picture 作为 CSS 选择器。该错误是指其他一些代码。
猜你喜欢
  • 1970-01-01
  • 2019-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多