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

标签 python google-app-engine beautifulsoup urllib

我有这个代码来提取标题:

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/

相关文章:

python - 使用旧 python 版本的 mod_wsgi 运行时

php - 我无法使用 GAE 在 Windows 上以本地模式运行 WordPress

Python BeautifulSoup 从 find_all() 返回错误的输入列表

http - Go 中的 Google App Engine 自定义 IP 端口

python - 无法访问 BeautifulSoup 中的表标签——显示为声明而不是标签

python - 使用 Python 抓取 NFL.com 梦幻足球预测

python 将列表写入文件

python 模拟补丁装饰器对于类方法和单个函数的行为不同

python - 拆分行并计算 pandas 中的新值

google-app-engine - GAE : What's the difference between <min-pending-latency> and <max-pending-latency>?