前提
Pythonを使用し、スクレイピングについて学習しています。
あるサイトから文字列の抽出を行いたいのですが、該当箇所のtypeがbs4.element.ResultSetであり、~.textを使用した文字列の抽出ができません。
実現したいこと
<html>[<h2 class="fa_ttl"><span class="fa_name"><a href="/dtl/00000000000000396895/" onclick="doSetCookie('61','','','00000000000000396895')">大久保北中学校</a></span></h2>]
というhtmlで書かれた文から「大久保北中学校」という文字列のみを抽出したいです。
- ▲▲機能を動作するようにする
発生している問題・エラーメッセージ
エラーメッセージ
AttributeError Traceback (most recent call last)
Input In [124], in <cell line: 1>()
----> 1 facility_name.text
File ~/opt/anaconda3/lib/python3.9/site-packages/bs4/element.py:2289, in ResultSet.getattr(self, key)
2287 def getattr(self, key):
2288 """Raise a helpful exception to explain a common code fix."""
-> 2289 raise AttributeError(
2290 "ResultSet object has no attribute '%s'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?" % key
2291 )
AttributeError: ResultSet object has no attribute 'text'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?
該当のソースコード
facility_name=facility.find_all('h2',attrs={'class': 'fa_ttl'})
facility_name.text
facility_nameには
[<h2 class="fa_ttl"><span class="fa_name"><a href="/dtl/00000000000000396895/" onclick="doSetCookie('61','','','00000000000000396895')">大久保北中学校</a></span></h2>]
が入っています。
試したこと
正規表現を用いて末尾「中学校」からの抽出を試みました。
しかし、facility_nameのtypeがbs4.element.ResultSetであり、文字列を抽出することができませんでした。
補足情報(FW/ツールのバージョンなど)
Jupiter LabおよびPython3を使用しています
回答1件
あなたの回答
tips
プレビュー