beautifulsoupの2つの「findAll」検索ブロックを1つに結合できますか?
-
22-07-2019 - |
質問
これら2つのブロックを1つにまとめることはできますか
編集:Yacobyが答えでしたように、ループを組み合わせる以外の方法。
for tag in soup.findAll(['script', 'form']):
tag.extract()
for tag in soup.findAll(id="footer"):
tag.extract()
複数のブロックを1つにすることもできます:
for tag in soup.findAll(id="footer"):
tag.extract()
for tag in soup.findAll(id="content"):
tag.extract()
for tag in soup.findAll(id="links"):
tag.extract()
または、ラムダ式が存在する可能性があります。ここで、配列またはその他の単純なメソッドであるかどうかを確認できます。
また、クラスは予約キーワードであるため、どのように属性クラスを持つタグを見つけるのですか:
編集:この部分はsoup.findAll(attrs = {'class': 'noprint'})によって解決されます:
for tag in soup.findAll(class="noprint"):
tag.extract()
解決
次のような関数を .findall()
に渡すことができます:
soup.findAll(lambda tag: tag.name in ['script', 'form'] or tag['id'] == "footer")
しかし、最初にタグのリストを作成し、それを繰り返し処理する方が良いかもしれません:
tags = soup.findAll(['script', 'form'])
tags.extend(soup.findAll(id="footer"))
for tag in tags:
tag.extract()
複数の id
でフィルタリングする場合は、次を使用できます。
for tag in soup.findAll(lambda tag: tag.has_key('id') and
tag['id'] in ['footer', 'content', 'links']):
tag.extract()
より具体的なアプローチは、ラムダを id
パラメーターに割り当てることです。
for tag in soup.findAll(id=lambda value: value in ['footer', 'content', 'links']):
tag.extract()
他のヒント
BeautifulSoupがもっとエレガントにできるかどうかはわかりませんが、2つのループを次のようにマージできます。
for tag in soup.findAll(['script', 'form']) + soup.findAll(id="footer"):
tag.extract()
そのようなクラスを見つけることができます(ドキュメント):
for tag in soup.findAll(attrs={'class': 'noprint'}):
tag.extract()
質問の2番目の部分に対する回答は、
CSSクラスによる検索
attrs引数は、CSSという1つの目的ではない場合、かなりあいまいな機能になります。特定のCSSクラスを持つタグを検索することは非常に便利ですが、CSS属性の名前であるクラスもPythonの予約語です。
soup.find(" tagName&quot ;, {" class":" cssClass"})を使用してCSSクラスで検索できますが、このような一般的な操作には多くのコードがあります。代わりに、辞書の代わりにattrsに文字列を渡すことができます。文字列は、CSSクラスを制限するために使用されます。
from BeautifulSoup import BeautifulSoup soup = BeautifulSoup("""Bob's <b>Bold</b> Barbeque Sauce now available in <b class="hickory">Hickory</b> and <b class="lime">Lime</a>""") soup.find("b", { "class" : "lime" }) # <b class="lime">Lime</b> soup.find("b", "hickory") # <b class="hickory">Hickory</b>
links = soup.find_all('a',class_='external') ,we can pass class_ to filter based on class values
from bs4 import BeautifulSoup
from urllib.request import urlopen
with urlopen('http://www.espncricinfo.com/') as f:
raw_data= f.read()
soup= BeautifulSoup(raw_data,'lxml')
# print(soup)
links = soup.find_all('a',class_='external')
for link in links:
print(link)