【问题标题】:Python XMl Parser with BeautifulSoup. How do I remove tags?带有 BeautifulSoup 的 Python XML 解析器。如何删除标签?
【发布时间】:2011-07-17 00:27:08
【问题描述】:

对于一个项目,我决定制作一款帮助人们在 Twitter 上找到朋友的应用程序。

我已经能够从 xml 页面中获取用户名。例如,使用我当前的代码,我可以从 XML 页面获取 <uri>http://twitter.com/username</uri>,但我想使用 Beautiful Soup 删除 <uri></uri> 标签。

这是我当前的代码:

import urllib
import BeautifulSoup

doc = urllib.urlopen("http://search.twitter.com/search.atom?q=travel").read()

soup = BeautifulStoneSoup(''.join(doc))
data = soup.findAll("uri")

【问题讨论】:

  • 以下任何一个答案有帮助吗?

标签: python beautifulsoup


【解决方案1】:

不要使用 BeautifulSoup 来解析 twitter,使用他们的 API(也不要使用 BeautifulSoup,使用 lxml)。回答你的问题:

import urllib
from BeautifulSoup import BeautifulSoup

resp = urllib.urlopen("http://search.twitter.com/search.atom?q=travel")
soup = BeautifulSoup(resp.read())
for uri in soup.findAll('uri'):
    uri.extract()

【讨论】:

  • 你给我的代码在 twitter.com/username 之间仍然有 Uri 标签
  • 不应该,所有标签都应该从soupstr(soup).find('uri') == -1剥离。
【解决方案2】:

要回答您关于 BeautifulSoup 的问题,text 是您获取每个 <uri> 标记内容所需的内容。在这里,我将信息提取到列表理解中:

>>> uris = [uri.text for uri in soup.findAll('uri')]
>>> len(uris)
15
>>> print uris[0]
http://twitter.com/MarieJeppesen

但是,as zeekay saysTwitter's REST API 是查询 Twitter 的更好方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 2017-03-31
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 2011-04-04
    相关资源
    最近更新 更多