我正在尝试从该网站中提取一些信息,即显示以下内容的行:
规模(处女座+ GA + Shapley):29 pc / arcsec = 0.029 kpc / arcsec = 1.72 kpc / arcmin = 0.10 Mpc /度
但:之后的所有内容都取决于galtype。
我已经编写了一个代码,该代码使用beautifulsoup和urllib并返回了一些信息,但是我正努力将数据进一步缩减为我想要的信息。如何获取所需的信息?
galname='M82'
a='http://ned.ipac.caltech.edu/cgi-bin/objsearch?objname='+galname+'&extend'+\
'=no&hconst=73&omegam=0.27&omegav=0.73&corr_z=1&out_csys=Equatorial&out_equinox=J2000.0&obj'+\
'_sort=RA+or+Longitude&of=pre_text&zv_breaker=30000.0&list_limit=5&img_stamp=YES'
print a
import urllib
f = urllib.urlopen(a)
from bs4 import BeautifulSoup
soup=BeautifulSoup(f)
soup.find_all(text=re.compile('Virgo')) and soup.find_all(text=re.compile('GA')) and soup.find_all(text=re.compile('Shapley'))
最佳答案
定义一个正则表达式模式,该模式将帮助BeautifulSoup
查找合适的节点,然后使用保存组提取数字:
pattern = re.compile(r"D \(Virgo \+ GA \+ Shapley\)\s+:\s+([0-9\.]+)")
print pattern.search(soup.find(text=pattern)).group(1)
打印
5.92
。此外,通常我反对使用正则表达式来解析HTML,但是,由于这是文本搜索,因此我们不会使用正则表达式来匹配开始或结束标记或与HTML提供的结构相关的任何内容-您可以将您的模式应用于页面的HTML源,而不涉及HTML解析器:
data = f.read()
pattern = re.compile(r"D \(Virgo \+ GA \+ Shapley\)\s+:\s+([0-9\.]+)")
print pattern.search(data).group(1)
关于python - 使用python urllib和漂亮的汤从html网站提取信息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30129895/