Pythonのスクレイピングに関して質問です。
以下のHTMLはとあるニュースサイトのもので、<article>タグの中の<div>タグ中の<a>タグのテキストを抽出しようと頑張ってみたのですが、出力が1行で終わってしまい、困っています。
HTML
1 <article class="story-list-story" data-id="PHWVVJ6S972901" data-type="article" data-updated-at="2018-11-09T22:08:37.536Z"> 2 3 <div class="story-list-story__info"> 4 5 6 <div class="story-list-story__info__headline"> 7 <a class="story-list-story__info__headline-link" href="/news/articles/2018-11-09/PHWVVJ6S972901?srnd=cojp-v2">【米国株・国債・商品】株下落、ハイテク売られる-国債は高い</a> 8 </div> 9 <span class="story-list-story__info__byline">Brendan Walsh、Natasha Doff</span> 10 11 <time class="hub-timestamp" itemprop="dateModified" datetime="2018-11-09T22:08:37.536Z" data-locale="ja" data-status="do-not-localize"> 12 2018年11月10日 7:08 JST 13 </time> 14 15 <div class="story-list-story__info__summary"></div> 16 17 </div> 18 19 20 </article> 21 22
↑元のニュースサイトではこの<article>タグで閉じられたニュースのヘッドラインが複数個続く
python
1 2import requests 3from bs4 import BeautifulSoup 4 5url = "https://www.bloomberg.co.jp/" 6 7response = requests.get(url) 8response.encoding = response.apparent_encoding 9 10 11 12bs = BeautifulSoup(response.text, "html.parser") 13 14article_story_list_story = bs.select("article.story-list-story") 15 16 17for div_story in article_story_list_story[0].select("div.story-list-story__info__headline"): 18 19 item_name_tags = div_story.select("a.story-list-story__info__headline-link") 20 item_name_tag = item_name_tags[0] 21 item_name = item_name_tag.text.strip() 22 print(item_name) 23 24 25
↑実際に私が書いたPythonのコード
長くなるのでHTMLは省略しますが、要約すると、複数のニュースのヘッドラインが出力されるはずが、最初の一つしか出力されなくて困っている、ということです。
よろしくお願いいたします、
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/11/11 06:40