bin*_*olo 5 python beautifulsoup
我在Python下使用BeautifulSoup进行了大量的数据抓取和清理工作,并且经常将其追加.text.strip()到soup.find命令中。例:foo_stuff = soup.find("foo").text.strip()
在某些情况下,a soup.find找不到任何东西,结果.text.strip()中断了。正如我所看到的,我可以通过几种方法来处理:
.find总是返回某些内容的查询- 我不是一个足够聪明的人,无法以一种简洁的方式设计这样的查询。.text.strip()- 代码很难看。.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)
写一个普通的旧函数怎么样?
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
| 归档时间: |
|
| 查看次数: |
5988 次 |
| 最近记录: |