python - 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”}“
该怎么办 ?
解决方案
鉴于您提供的代码,我认为您可以组合不同的过滤器并完全避免该问题。您正在寻找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 选择器参考
推荐阅读
- c - 如何在 C 中打印 ASN.1 UPER 消息字段的字段?
- javascript - Vue js 将外部脚本文件添加到我的应用程序
- r - dplyr semi_join 错误:`x` 和 `y` 必须共享同一个 src,设置 `copy` = TRUE(可能很慢)
- google-cloud-functions - 接收(我的应用程序名称)现在没有响应。使用云功能部署时,请稍后再试
- r - tidyr:分隔列,同时在第一列中保留分隔符
- javascript - 正确处理 THREE.JS 中的曲线
- magento2 - 为 Magento 2 商店安装 Shipstation 插件时出错
- python - 在 Python 中将 5 x 16 列数据框乘以 5 x 1 列数据框
- c# - C# 在文件中存储/加载 guid 列表
- azure-functions - 在服务总线上运行进程时,主机已被处置,无法使用