使用python urllib和美丽的汤从html网站中提取信息

时间:2015-05-08 17:51:01

标签: python beautifulsoup urllib

我正试图从这个网站中提取一些信息,即:

比例(Virgo + GA + Shapley):29 pc / arcsec = 0.029 kpc / arcsec = 1.72 kpc / arcmin = 0.10 Mpc / degree

但是后面的所有内容都是可变的,具体取决于galtype。

我编写了一个使用beautifulsoup和urllib并返回sone信息的代码,但我正在努力将数据进一步减少到我想要的信息。我如何获得我想要的信息?

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'))

1 个答案:

答案 0 :(得分:1)

定义一个正则表达式模式,帮助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)