开发者

Parsing XML with BeautifulSoup and handling missing element

开发者 https://www.devze.com 2022-12-19 22:16 出处:网络
I am using BeautifulSoup to parse XML: xml = \"\"\"<person> <first_name>Matt</first_name>

I am using BeautifulSoup to parse XML:

xml = """<person>
<first_name>Matt</first_name>
</person>"""

soup = BeautifulStoneSoup(xml)
first_name = soup.find('first_name').string
last_name = soup.find('last_name').string

But I have a problem when there is no last_name, because it chokes. Sometimes the feed has it, and sometimes it doesn't. How do I preve开发者_开发技巧nt it from choking?

I don't want to use try/except statements. I also do not want to use if/else statements. (Since it'll double the lines of the already-very-long code if I have those statements).

Is there any way to just return "None" if there is no "last_name"?


last_name = soup.find('last_name') and soup.find('last_name').string

Very silly, but it does meet your equally silly stated restriction (no if). A bit less silly:

last_name_node = soup.find('last_name')
last_name = last_name_node and last_name_node.string

and:

last_name = getattr(soup.find('last_name'), 'string', None)

These two don't have the same overhead as the first. I think a simple if is more readable than any of these, though.

0

精彩评论

暂无评论...
验证码 换一张
取 消