2017-06-12 11 views
0

は、私は、このページから必要な正しい情報を引っ張っていくつかの問題を抱えています:理想的http://www.chronicle.com/article/Major-Private-Gifts-to-Higher/128264BeautifulSoupを使用すると、段落内の特定のアイテムをどのようにターゲットできますか?

が、私は学校の名前や各学校に才能の値を取得したいと思います。例えばのために

:テクノロジーの 「カリフォルニア工科大学:ゴードンとベティ・ムーアとゴードンとベティ・ムーア財団、$ 600万人から、5年間で$ 300百万10年間で$ 300百万ドルからなる、現金と株式; 2001 *」

理想的な出力は次のようになります。テクノロジーの カリフォルニア工科大学、$ 600百万

(カンマで区切る)

答えて

1

あなたはBeautifulSoupを使ってこれを実装でき、 Regular Expressions

BeautifulSoupはHTMLとXMLデータの解析を可能にするpythonライブラリです。

正規表現では、文字列内の特定のパターンを検索できます。

from bs4 import BeautifulSoup 
import re 
import urllib.request 

link = 'http://www.chronicle.com/article/Major-Private-Gifts-to-Higher/128264' 
req = urllib.request.Request(link, headers={'User-Agent': 'Mozilla/5.0'}) 
sauce = urllib.request.urlopen(req).read() 
soup = BeautifulSoup(sauce, 'html.parser') 

university = {} 

for x in soup.find_all('p'): 
    name_tag = x.find('strong') 
    if name_tag != None: 
     name = name_tag.text 
     t = x.text 
     m = re.findall('\$([0-9]*)', t) 
     if m != []: 
      #There is a possibility that there are more than one values gifted. 
      #For example, in case of CalTech there are 3 values [600, 300, 300] 
      #This can be handled in two ways. 
      #Either print the first value using m[0]. 
      #Or find the max element of the list using max(m)   
      print(name +', ' + m[0]) 
+0

ありがとうございました!これは非常に理解しやすい/フォロースルーしました。 – dancemc15

関連する問題