【问题标题】:beautiful soup returns close tag instead of tag text美丽的汤返回关闭标签而不是标签文本
【发布时间】:2017-11-16 00:17:34
【问题描述】:

我有以下 RSS 源(soundcloud)http://feeds.soundcloud.com/users/soundcloud:users:7393028/sounds.rss

<item>
      <pubDate>Mon, 05 Jun 2017 00:00:00 +0000</pubDate>
      <link>https://example.com</link>
<item>

我尝试使用以下内容获取链接标签内容:

soup = BeautifulSoup(response, "lxml")


items = soup.findAll("item")
for i in items:
    print i
    created_at = i.find('pubdate')
    created_at = created_at.contents[0][:16]

    url = i.find('link')

This prints:

    <link/>

如果我尝试url = i.find('link').stringurl = i.find('link').content

我明白了

当我打印“i”项时,它首先为链接打印一个关闭标签:

https://soundcloud.com/daptone-records/sharon-jones-the-dap-kings-white-christmas 00:02:23 达通唱片 不 Sharon Jones 和 Dap-Kings 的第一张假日专辑现已发行!

如何让链接正常打开?

【问题讨论】:

  • 你能提供准确的网址吗?
  • @AzatIbrakov 我添加了链接。谢谢。

标签: python xml beautifulsoup lxml


【解决方案1】:

你可以做这样的事情,它会做的工作:

from bs4 import BeautifulSoup as bs 
from urllib.request import urlopen

url = 'http://feeds.soundcloud.com/users/soundcloud:users:7393028/sounds.rss'
data = urlopen(url).read()

parsed = bs(data, 'xml')
items = parsed.findAll('item')

for k in items:
    # Here is how you can access to the tags inside item tag
    print("Link:", k.link.text)
    print("pubDate:", k.pubDate.text)

编辑:使用lxml

当我尝试使用 BeautifulSouplxml 解析 &lt;link&gt;...&lt;/link&gt; 标签时,我得到了一个无效标签。每个链接的标签都以&lt;/link&gt; 开头,而BeautifulSoup 无法解析其数据。

所以,使用regex 是一个简单的破解方法,下面是一个示例:

from bs4 import BeautifulSoup as bs 
from urllib.request import urlopen
import re

url = 'http://feeds.soundcloud.com/users/soundcloud:users:7393028/sounds.rss'
data = urlopen(url).read()

soup = bs(data, 'lxml')
aa = soup.findAll('item')

for k in aa:
    link = re.findall('<link/>(.*?)\s+', str(k))
    pubdate = k.find('pubdate').string
    print("Link: {}\npubdate: {}".format(' '.join(link), pubdate))

两种方法都会输出:

Link: https://soundcloud.com/daptone-records/move-upstairs
pubDate: Tue, 21 Mar 2017 20:30:49 +0000
...
Link: https://soundcloud.com/daptone-records/the-frightnrs-id-rather-go-blind-1
pubDate: Sun, 28 Jun 2015 00:00:00 +0000

【讨论】:

  • LXML 可以做到这一点吗?
  • 如果是LXML,我可能会更改代码。我会更新我的答案
  • 是的,这就是我最终所做的。我猜漂亮的汤不适合声音云或那些链接标签。
  • 但是使用xml 很简单。我尝试使用这个tutorial,但没有任何成功。我想当我们使用lxml 时需要添加或修改一些东西,它与xml 解析器有点不同。但是,希望正则表达式可以解决这个问题......现在。
猜你喜欢
  • 2019-11-20
  • 1970-01-01
  • 2018-07-18
  • 2017-12-05
  • 1970-01-01
  • 1970-01-01
  • 2016-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多