前提・実現したいこと
pythonのbeatifulsoupを使って、htmlから内容部分をタグごと抜き出したいと思っています。内容を文字だけ抜き出すのは、調べると簡単に出てくるのですが、タグごと抜き出すのは見つけられませんでした。
発生している問題・エラーメッセージ
そこで次の2つの方法で解決しようとしました。
1.<p>タグかつ<h2>タグを要素に持つ<div>を抜き出す。
python
1content_with_tag = soup.select('div:has(>p h2)') 2print(content_with_tag)
実行すると空のリストが出力されてしまいます。
div:has(>p)やdiv:has(>h2)にするとそれぞれの条件でうまく出力されるので、pかつh2の書き方が悪いと思っています。beautifulsoupのドキュメントも調べたのですが、解決しませんでした。
2.1がうまくいかなかったので以下のコードで対応しようとしました。
python
1content_with_tag_p = soup.select('div:has(>p)') 2content_with_tag_p_h2 = content_with_tag_p.select('div:has(h2)') 3print(content_with_tag_p_h2)
先に<p>タグを要素に持つ<div>を選択して、そこからまた<h2>タグを要素に持つ<div>を抜き出そうとしましたが、「content_with_tag_p_h2」でattributeエラーが出てうまくいきませんでした。
問題のソースコード
python
1from selenium import webdriver 2from bs4 import BeautifulSoup 3 4driver = webdriver.Chrome('chromeドライバーがある場所') 5target_url = "https://www.verisign.com/en_US/website-presence/online/what-is-a-url/index.xhtml" 6driver.get(target_url) 7 8html = driver.page_source 9 10soup = BeautifulSoup(html, "lxml") 11 12content_with_tag_p = soup.select('div:has(>p)') 13content_with_tag_p_h2 = content_with_tag_p.select('div:has(h2)') 14 15print(content_with_tag_p_h2)
1と2の解決方法をそれぞれお願いできると助かります。よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/01/27 07:45