+-
python – 在BeautifulSoup中安全地.text.strip()的优雅方式?
我在 Python下使用BeautifulSoup进行相当多的数据抓取和清理,并经常将.text.strip()附加到soup.find命令.示例:foo_stuff = soup.find(“foo”).text.strip()

在某些情况下,soup.find找不到任何内容,并且生成的.text.strip()会中断.在我看来,我可以通过以下几种方式解决这个问题:

>写.总是返回一些东西的查询.我不是一个聪明的人,以干净的方式构建我的查询.
>在每个.text.strip()上使用try / except语句 – 代码很难看.
>我可以修补.find命令以获得try / except,或者包含执行类似操作的.myfind命令 – 这涉及到修补内容并可能会丢弃协作者.

其他人有没有更好/更聪明的解决方案来解决这个问题?

编辑:现在我正在使用一个无聊的ol’函数来尝试/除了.text.strip():

def text_strip(soup_search):
    if soup_search != None:
        return soup_search.text.strip()
    else:
        return ""
最佳答案
写一个普通的老函数怎么样?

def find_stripped(soup, what):
  found = soup.find(what)
  if found is not None:
    return found.text.strip()
  # maybe:
  # return ""

现在你可以:foo_stuff = find_stripped(汤,“foo”)

点击查看更多相关文章

转载注明原文:python – 在BeautifulSoup中安全地.text.strip()的优雅方式? - 乐贴网