find()でタグを検索する
soup.h1のような書き方の代わりに、find(タグ名)を使うと同じように「条件に一致する最初の1つ」を取得できます。find()の良いところは、タグ名だけでなく後のレッスンで習うclass名などの条件も細かく指定できる点です。
soup.h1のような書き方の代わりに、find(タグ名)を使うと同じように「条件に一致する最初の1つ」を取得できます。find()の良いところは、タグ名だけでなく後のレッスンで習うclass名などの条件も細かく指定できる点です。
from bs4 import BeautifulSoup
html = '<div><p>1つ目</p><p>2つ目</p></div>'
soup = BeautifulSoup(html, 'html.parser')
first_p = soup.find('p')
print(first_p.text)練習問題:'<ul><li>りんご</li><li>バナナ</li></ul>'というHTMLから、find()で最初のliタグのテキストを表示してください。
from bs4 import BeautifulSoup
html = '<ul><li>りんご</li><li>バナナ</li></ul>'
soup = BeautifulSoup(html, 'html.parser')
first_item = soup.find('li')
print(first_item.text)