[英]Deal with 'NoneType' object is not iterable' error in a list of comprehension
I'm trying to scrape quantity from a site using this code:我正在尝试使用以下代码从网站上抓取数量:
qty = [qty.text.strip() for qty in soup.find("span", attrs={"class":"item-quantity"})]
but the value is not always present so I'm getting this error:但该值并不总是存在,所以我收到此错误:
'NoneType' object is not iterable
is there a way to insert an if and else statement in a list of comprehension?有没有办法在理解列表中插入 if 和 else 语句? So that when the quantity is not present in the list the value "1" is saved.因此,当列表中不存在数量时,将保存值“1”。 I've tried我试过了
qty = [qty.text.strip() for qty in soup.find("span", attrs={"class":"item-quantity"})if x is not None else x="1"]
But I'm getting an error of invalid syntax但我收到无效语法错误
I highly recommend using a for loop here, but here's one way to do this我强烈建议在此处使用 for 循环,但这是执行此操作的一种方法
qty = [qty.text.strip() for qty in soup.find("span", attrs={"class":"item-quantity"}) or []]
Since None is Falsy, it evaluates the expression after or
由于 None 是 Falsy,它计算or
之后的表达式
print(None or []) # []
print([1,2,3] or []) # [1,2,3]
Try:尝试:
qt = [qty.text.strip() for qty in soup.find_all("span", attrs={"class":"item-quantity"}) if qty else "1"]
List comprehensions
have the ability to use ternary expressions
like this: List comprehensions
能够使用这样的ternary expressions
:
qty = [qty.text.strip() if qty else "1" for qty in soup.find("span", attrs={"class":"item-quantity"})]
It is also possible to use a normal loop and add try/except
instead of an if/else
.也可以使用普通循环并添加try/except
而不是if/else
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.