首页 > 解决方案 > 如何在遍历 webelements 时摆脱 None ?

问题描述

我正在尝试返回没有任何无的 web 元素列表。不知道为什么,但似乎pass不起作用。有任何想法吗?请。

顺便提一句。可以通过使用 Pandas 来修复它,但我想坚持使用纯 Python/Selenium 并了解问题所在。

def get_(article):
    try:
        article.find_element_by_xpath(".//a[div[@class='accessible_elem']]")
    except NoSuchElementException:
        pass
    else:
        title = article.find_element_by_xpath(".//a[div[@class='accessible_elem']]").get_attribute('aria-label')
        pubdate = article.find_element_by_xpath(".//abbr").get_attribute('data-utime')
        url = article.find_element_by_xpath(".//a[div[@class='accessible_elem']]").get_attribute('href')
        return(title, pubdate, url)

output = []
for article in articles:
    content = get_(article)
    output.append(content)

在此处输入图像描述

标签: pythonseleniumexceptionweb-scraping

解决方案


问题:您NoSuchElementException有时不会被抓住,因为没有抛出 NoSuchElementException。一个例子是,如果一个具有类的元素accessible_elem存在但没有您读取的正确属性。此外,当您因异常而通过时,该函数将返回 None。

修复:这取决于,但您可能想先检查内容是否为无,然后在附加之前检查标题、发布日期或网址中的任何一个是否为无。将您的 for 循环更改为:

for article in articles:
  content = get_(article)
  if content and all([x is not None for x in content]):
    output.append(content)

您可以将检查缩短为:

if content and all(content):

如果你知道你永远不会得到任何元组值的值 0(一个假值)。


推荐阅读