python - 如何在遍历 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)
解决方案
问题:您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(一个假值)。
推荐阅读
- .net - Implement lambda layer in lambda function using .net
- python - How can I maintain Django database entries after making migrations and pushing changes to Git?
- r - How do you remove the academic and demos sections from the main page of the Academic hugo theme when using blogdown?
- teradata - Teradata - Calculate the previous quarter date start date and end date from current date
- ibm-cloud - 如何在 Gstreamer (Python) 中流式传输音频
- google-bigquery - 如何将公共数据集导入 Google Cloud Bucket
- android - 凌空请求处理后做一些事情
- ruby-on-rails - Rails:如果选中复选框,如何将值“9999-99-99”传递到日期?
- google-ad-manager - 有没有办法在 Google AdManger 中制作 HTML5 广告“宽度:100%”?
- php - 在 PHP 中使用 AJAX 设置 If 语句