【问题标题】:Beautifulsoup html parsing corrupts a <link> tagBeautifulsoup html 解析损坏了 <link> 标签
【发布时间】:2019-07-20 21:20:15
【问题描述】:

我正在使用漂亮的汤从 rss 页面解析 html 代码。如何保留链接标签?

最有希望的代码是:

python
import urllib.request, urllib.parse, urllib.error 
from bs4 import BeautifulSoup
url = 'https://advisories.ncsc.nl/rss/advisories'
uh = urllib.request.urlopen(url)
html_doc= uh.read()
soup = BeautifulSoup(html_doc, 'html.parser')

我试过import lxml 并将代码切换到 python soup = BeautifulSoup(html_doc, 'xml') 但这给了我一个错误:

ModuleNotFoundError: No module named 'lxml'

我希望结果是 &lt;link&gt;https://someurl.org&lt;/link&gt;但输出是&lt;link/&gt;someurl.org

【问题讨论】:

  • 什么结果?你不用soup做任何事情。
  • print(soup) 的结果,应该加了。

标签: python beautifulsoup xml-parsing


【解决方案1】:

您正在尝试解析rss feed,为此您可以使用feedparser,即:

import feedparser, requests
feed_xml = requests.get("https://advisories.ncsc.nl/rss/advisories").text
feed = feedparser.parse(feed_xml)
print ('Number of RSS posts :', len(feed.entries))
for entry in feed.entries:
    print (entry.title)
    print (entry.link)
    print (entry.description)

输出:

Number of RSS posts : 25
NCSC-2019-0098 [1.02] [H/M] Kwetsbaarheid verholpen in libreoffice
https://advisories.ncsc.nl/advisory?id=NCSC-2019-0098
Een kwaadwillende kan de kwetsbaarheid mogelijk misbruiken om willekeurige code uit te voeren onder de rechten van een gebruiker.
...

使用pip 安装feedparser

pip install feedparser

【讨论】:

    【解决方案2】:

    将解析器更改为 xml 修复了 &lt;link&gt; 标签:

    import urllib.request, urllib.parse, urllib.error
    from bs4 import BeautifulSoup
    url = 'https://advisories.ncsc.nl/rss/advisories'
    uh = urllib.request.urlopen(url)
    html_doc= uh.read()
    soup = BeautifulSoup(html_doc, 'xml')    # <-- changing to 'xml'
    
    for link in soup.select('link'):
        print(link.get_text(strip=True))
    

    打印:

    https://advisories.ncsc.nl/rss/advisories
    https://advisories.ncsc.nl/advisory?id=NCSC-2019-0098
    https://advisories.ncsc.nl/advisory?id=NCSC-2019-0584
    https://advisories.ncsc.nl/advisory?id=NCSC-2019-0511
    https://advisories.ncsc.nl/advisory?id=NCSC-2019-0583
    https://advisories.ncsc.nl/advisory?id=NCSC-2019-0560
    https://advisories.ncsc.nl/advisory?id=NCSC-2019-0546
    
    ...and so on.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-24
      • 2013-03-20
      • 2012-05-22
      相关资源
      最近更新 更多