2016-04-13 12 views
0

PythonでBeautifulSoupを使用して、ページのソースコードから時間範囲を取得しようとしています。BeautifulSoup - クラスを見つけて別のクラスを除外

私はこの

<span class="experience-date-locale"><time>June 2010</time> – <time>August 2010</time> (3 months)<span class="locality">New York</span></span> 

<span class="experience-date-locale"><time>October 2015</time> – Present (7 months)</span> 

<span class="experience-date-locale"><time>May 2010</time> – <time>October 2011</time> (6 months)</span> 

のように見える解析しようとしていると私はいつか私も「地域」クラスを持つbecuase私はdidntの仕事をしようとした右

この行を、それを取得する方法を知らないライン...

soup.find('span', {'class': 'experience-date-locale'}).text 

これは私が 'が存在' 部分

を欠場becuaseあまりにも動作しません。

場所の一部を除外して時間を取得するにはどうすればよいですか?

結果は次のようになります。

June 2010 - August 2010 (3 months) 

October 2015 - present (7 months) 

May 2010 - October 2011 (6 month) 
+0

第二のスニペットの結果は何ですか? –

+0

@LutzHornはAttributeErrorをスローします。実際には、実際には日付が "現在"ある場合、それが問題を解決しない原因となるのを助けてくれません –

+0

以下の回答のいずれかが役に立ちますか? –

答えて

1

あなたはそれがあるとき、余分な<span>タグを削除しようとすることができます。

from bs4 import BeautifulSoup 

html = '''<span class="experience-date-locale"><time>June 2010</time> – <time>August 2010</time> (3 months)<span class="locality">New York</span></span> 
<span class="experience-date-locale"><time>October 2015</time> – Present (7 months)</span> 
<span class="experience-date-locale"><time>May 2010</time> – <time>October 2011</time> (6 months)</span>''' 

soup = BeautifulSoup(html) 
for e in soup.find_all('span', {'class': 'experience-date-locale'}): 
    if e.span: 
     _ = e.span.extract() 
    print(e.text) 

出力が

June 2010 – August 2010 (3 months) 
October 2015 – Present (7 months) 
May 2010 – October 2011 (6 months) 

これは、あなたが望むの出力が得られます、しかし、それはドキュメントツリーを変更しません。

0

これを試してみてください:

for span in soup.findAll("span", {"class": "experience-date-locale"}): 
    for child in span.contents: 
     if isinstance(child, bs4.element.Tag) and child.name == "time": 
      print(child.text, end='') 
     elif isinstance(child, bs4.element.NavigableString): 
      print(child, end='') 
    print() 

出力:

June 2010 – August 2010 (3 months) 
October 2015 – Present (7 months) 
May 2010 – October 2011 (6 months) 
関連する問題