Python 3 Beautiful Soup 用冒号查找标签

Python 3 Beautiful Soup find tag with colon

我正在尝试抓取该网站并获取两个单独的标签。这就是 html 的样子。

<url>
  <loc>
    http://link.com
  </loc>
  <lastmod>date</lastmode>
  <changefreq>daily</changefreq>
  <image:image>
   <image:loc>
    https://imagelink.com
   <image:loc>
   <image:title>Item title</image:title>
  <image:image>
</url>

我要获取的标签是 loc 和 image:title。我遇到的问题是标题标签中的冒号。我目前的代码是

r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')

for item in soup.find_all('url'):
    print(item.loc)
    #print image title

我也试过

print(item.title)

但这不起作用

您应该在 "xml" mode 中解析它(还需要安装 lxml):

from bs4 import BeautifulSoup

data = """
<url>
  <loc>
    http://link.com
  </loc>
  <lastmod>date</lastmod>
  <changefreq>daily</changefreq>
  <image:image>
   <image:loc>
    https://imagelink.com
   </image:loc>
   <image:title>Item title</image:title>
  </image:image>
</url>"""

soup = BeautifulSoup(data, 'xml')

for item in soup.find_all('url'):
    print(item.title.get_text())

打印 Item title.

请注意,我已经对您的 XML 字符串进行了多项修复,因为它最初的格式不正确。

我正在使用 BeautifulSoup 解析 Confluence XHTML,而 alecxe 的解决方案并不令我满意,因为我确实需要 BeautifulSoup 的 html 模式。

所以我找到了一个使用正则表达式的 hacky 解决方案:

>>> import re
>>> from bs4 import BeautifulSoup
>>>
>>> data = """
... <url>
...   <loc>
...     http://link.com
...   </loc>
...   <lastmod>date</lastmod>
...   <changefreq>daily</changefreq>
...   <image:image>
...    <image:loc>
...     https://imagelink.com
...    </image:loc>
...    <image:title>Item title</image:title>
...   </image:image>
... </url>"""
>>>
>>> soup = BeautifulSoup(data, 'html.parser')
>>> soup.find_all('image:title')  # nope, bs4 won't allow us to do this
[]
>>> soup.find_all(re.compile('image:title'))  # but this works
[<image:title>Item title</image:title>]