【问题标题】:Get CDATA from BeautifulSoup Python从 BeautifulSoup Python 获取 CDATA
【发布时间】:2019-05-10 18:11:04
【问题描述】:

我有一个带有 CDATA 标记的 HTML 源代码,其中包含我想要的一些信息。

当我尝试以下操作时:

switch_url = switch_soup.find_all(text=re.compile(('Switches')))

我得到这个输出:

['//<![CDATA[\n    "url":"https://xxxx.meraki.com/xxxxxxx/n/xxxxx/manage/nodes/list","name":"Switches","admin_only":false},{"is_current":false,"url":"https://nxx.meraki.com/xxxxx/n/xxxxx/manage/configure/switchports","name":"Switch ports","admin_only":false},{"is_current":false,"url":"https://xxxx.meraki.com/Dormitory/n/xxxxxxx/manage/configure/dhcp_servers"//]]>\n  ']

如何从 CDATA 输出中获取“Switches”网址,即:“https://xxxx.meraki.com/xxxxxxx/n/xxxxx/manage/nodes/list”?

提前致谢!

【问题讨论】:

    标签: python beautifulsoup cdata


    【解决方案1】:

    你需要的是这个

    from BeautifulSoup import BeautifulSoup
    import re
    
    // source.html contains your html above
    f = open('source.html')
    soup = BeautifulSoup(''.join(f.readlines()))
    cdata = soup.find(text=re.compile("CDATA"))
    

    或者你可以试试这个

    for script in soup(['script', 'style']):
            script.decompose()
    
        text = soup.get_text()
        lines = (line.strip() for line in text.splitlines())
        chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
        text = '\n'.join(chunk for chunk in chunks if chunk)
    

    【讨论】:

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