在BeautifulSoup中安全地.text.strip()的优雅方法?

bin*_*olo 5 python beautifulsoup

我在Python下使用BeautifulSoup进行了大量的数据抓取和清理工作,并且经常将其追加.text.strip()到soup.find命令中。例:foo_stuff = soup.find("foo").text.strip()

在某些情况下,a soup.find找不到任何东西,结果.text.strip()中断了。正如我所看到的,我可以通过几种方法来处理:

  • 编写.find总是返回某些内容的查询- 我不是一个足够聪明的人,无法以一种简洁的方式设计这样的查询。
  • 在每个代码上使用try / except语句.text.strip()- 代码很难看。
  • 我可以修补.find命令以具有try / except或包括.myfind执行类似操作的命令- 这涉及到我修补事物并可能抛弃协作者。

那里的其他人是否有更好/更聪明的解决方案来解决此问题?

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

def text_strip(soup_search):
    if soup_search != None:
        return soup_search.text.strip()
    else:
        return ""
Run Code Online (Sandbox Code Playgroud)

900*_*000 5

写一个普通的旧函数怎么样?

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

现在你可以: foo_stuff = find_stripped(soup, "foo")


小智 5

现在有一种真正更好的方法,更安全。

my_str = soup.find("span").get_text(strip = True)
Run Code Online (Sandbox Code Playgroud)

请参阅https://beautiful-soup-4.readthedocs.io/en/latest/index.html?highlight=strip#get-text