如何使用美丽的汤从 html 获取 CData

时间:2020-12-19 00:04:17

标签: python beautifulsoup request

我正在尝试从网页中获取值。网页源代码中,数据为CDATA格式,同样来自jQuery。我设法编写了以下代码,该代码获得了大量文本,其中索引 21 包含我需要的信息。但是,这个输出很大,而且不是我理解的格式。在输出中我需要隔离和输出 "redshift":"0.06" 但不知道如何。解决此问题的最佳方法是什么。

import requests
from bs4 import BeautifulSoup

link = "https://wis-tns.weizmann.ac.il/object/2020aclx"  

html = requests.get(link).text

soup = BeautifulSoup(html, "html.parser")
res = soup.findAll('b')

print soup.find_all('script')[21]

3 个答案:

答案 0 :(得分:1)

可以使用您现有的方法来完成。但是,我建议不要这样做。有一种更简洁的方法可以通过观察红移值出现在页面本身的几个方便的位置来实现。

以下方法应该适合您。它在带有 table “atreps-results-table”的页面上查找 class - 其中有两个。我们采用第二个这样的表格并查找具有“cell-redshift”类的表格单元格。然后,我们只是打印出它的文本内容。

from bs4 import BeautifulSoup

import requests

link = 'https://wis-tns.weizmann.ac.il/object/2020aclx'
html = requests.get(link).text
soup = BeautifulSoup(html, 'html.parser')
tab = soup.find_all('table', {'class': 'atreps-results-table'})[1]
redshift = tab.find('td', {'class': 'cell-redshift'})
print(redshift.text)

答案 1 :(得分:0)

简单地尝试:

soup.select_one('div.field-redshift > div.value>b').text

答案 2 :(得分:0)

如果查看 URL 的 Page Source,您会发现有两个脚本元素具有 CDATA。但是您感兴趣的脚本元素中包含 jQuery。所以你必须根据这些知识来选择脚本元素。之后,您需要进行一些清理以摆脱 CDATA 标签和 jQuery。然后借助 json 库,将 JSON 数据转换为 Python Dictionary。

import requests
from bs4 import BeautifulSoup
import json

page = requests.get('https://wis-tns.weizmann.ac.il/object/2020aclx')
htmlpage = BeautifulSoup(page.text, 'html.parser')
scriptelements = htmlpage.find_all('script')
for script in scriptelements:
  if 'CDATA' in script.text and 'jQuery' in script.text:
    scriptcontent = script.text.replace('<!--//--><![CDATA[//>', '').replace('<!--', '').replace('//--><!]]>', '').replace('jQuery.extend(Drupal.settings,', '').replace(');', '')
    break
jsondata = json.loads(scriptcontent)
print(jsondata['objectFlot']['plotMain1']['params']['redshift'])