And*_*rew 6 python string parsing beautifulsoup
如果问题标题过于模糊,请道歉 - 欢迎编辑.
我正在尝试使用BeautifulSoup解析XML,但因为每个函数调用都可以返回None,所以我必须在多行上解析单个元素.这很快变得笨拙:
books_count = result.books_count
if not books_count:
return None
books_count = books_count.string
if not books_count:
return None
books_count = int(books_count)
if not books_count:
return None
Run Code Online (Sandbox Code Playgroud)
在Swift中做同样的事情,这是一种我更熟悉的语言,它更清晰:
guard let booksCountString = result.booksCount?.string,
let booksCountInt = Int(booksCountString) else {
return nil
}
Run Code Online (Sandbox Code Playgroud)
有没有类似的方法我可以用Python做到这一点?我想避免使用try/catch导致它在我的代码中不断出现运行时错误并不是一种好的做法.
也许在 for 循环中?
\n\nexample = [result.books_count, books_count.string, int(books_count)]
for n in example:\n if not n : return None\n
刚刚测试过,只要result.books_count, books_count.string, int(books_count)are\xc2\xb4t 引发任何错误, for 循环就可以正常工作
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |