【发布时间】:2021-02-13 22:59:34
【问题描述】:
我正在尝试返回没有任何 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)
【问题讨论】:
-
if title is None: pass,否则...应该可以工作。请注意,一篇文章可能存在,但具有None作为您要求的属性的值。 -
关键元素在 try: 语句中。其余的应该在 True 时执行。当然有些文章没有 class='accessible_elem'。
标签: python selenium exception web-scraping