用两个封闭标签之间的美味汤来解析内容
我使用BeautifulSoup来解析网页中的艺术家和相册信息的内容。我已经下来分析的信息是:用两个封闭标签之间的美味汤来解析内容
`<span dir="ltr"><a href="unique?id=1234">Jay-Z</a> & <a href="unique?id" = 321">Kanye West</a> - Watch the Throne</span>`
专辑名称(在这种情况下,“观看王座”)始终是关闭</span>
标记之前。
无论相册中包含多少艺术家,无论是单个艺术家还是30位艺术家,我都需要解析整个<span>
元素中的专辑数据。
困难在于专辑名称介于两个结束标签元素之间。
任何想法?
>>> from BeautifulSoup import BeautifulSoup
>>> html = '''<span dir="ltr"><a href="unique?id=1234">Jay-Z</a> &
... <a href="unique?id" = 321">Kanye West</a> - Watch the Throne</span>'''
>>> soup = BeautifulSoup(html)
>>> soup.span.contents[-1].strip('- ')
u'Watch the Throne'
如果我理解正确,专辑名称将始终在span元素的末尾。您可以尝试查找最后一个关闭a-tag的索引,以及span-tag结束的最后一个索引,并从中创建一个包含相册信息的字符串。
因此,使用theString.rfind("</a>")
,您会发现起始索引和theString.rfind("</span>")
以查找结束索引。
这正是我所需要的信息。我对python相当陌生,并且非常专注于让BeautifulSoup去做肮脏的工作,我忘记了能够在字符串中找到范围。谢谢! –
但你并不真的需要这个 - 你可以使用原生的BeautifulSoup来解决这个问题 - 会更短,更优雅,我相信 – alonisser
是的,你是对的。 BeautifulSoup可以做到这一点。你下面的人和我一起清除它。谢谢! –
如果s是汤元,则:
album = s.findAll('a')[-1].nextSibling
我想你可以清理“ - ”自己 好运气,我爱beautifulsoup
这绝对是做到这一点的方法。非常感谢。 BeautifulSoup是一个了不起的工具。它几乎太简单了。我只是让我的方法过于复杂。 –