gpt4 book ai didi

python - 如何从页面的标题标签中删除换行符和换行符? (谷歌应用引擎 - Python)

转载 作者:行者123 更新时间:2023-11-28 22:05:24 25 4
gpt4 key购买 nike

我有这段代码可以提取标题:

soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))
title = str(soup.html.head.title.string).lstrip("\r\n").rstrip("\r\n")

有些网站在标题标签前后添加回车符或换行符(为什么?)并删除它们我添加了

.lstrip("\r\n").rstrip("\r\n")

这适用于例如 http://www.readwriteweb.com/但不是 http://poundwire.com/ .你能说出为什么一个有效而另一个无效吗?

更新

跟进 Steve Jessop 的评论;我正在使用 replace 并且它似乎有效:

title = str(soup.html.head.title.string).replace("\t", "").replace("\r", "").replace("\n", "")

如果有更好的方法,请告诉我。谢谢。

更新 2

我找到了这个 answer看起来更好:

title = " ".join(str(soup.html.head.title.string).split())

最佳答案

尝试使用 str(title).strip(),它将去除字符串开头和结尾的所有空格。

关于python - 如何从页面的标题标签中删除换行符和换行符? (谷歌应用引擎 - Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5426523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com