sample code

list = [i.get('content').encode('utf-8') for i in self.soup.find_all('meta',attrs={"name": "description"})]

The problem is that .encode('utf-8') will raise an error:

AttributeError: 'NoneType' object has no attribute 'encode'

if one of the elements of the list is None.

I am wondering if there is a 'pythonic' way of keeping it in one line and ignoring None elements. For example can you put a if not None clause in the list? Thanks.

有帮助吗?

解决方案

I would break this up into a generator expression for the initial fetching to limit the lookup, so get is only called once for performance.

items_i = (i.get('content') for i in self.soup.find_all('meta',attrs={"name": "description"}))
items = [i.encode('utf-8') for i in items_i if i]

其他提示

you can give .get a default argument to use instead of None

[i.get('content','').encode('utf-8') for i in self.soup.find_all('meta',attrs={"name": "description"})]

or you can filter it out

[i.get('content').encode('utf-8') for i in self.soup.find_all('meta',attrs={"name": "description"}) if i.get('content') is not None]

you should note that its not i that is none but rather its 'content'

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top