問題点
Yahooニュースのコメントをスクレイピングしたいです。
現状、Yahoo.co.jpのサイトの中から特定のキーワードを含むものを見つけてそのタイトルとURLを読み取ります。そして、そのURLを更に読み取ってニュースの個別ページに行き、その中からコメントに当たる部分を取ってこようとしています。
しかし、右クリックからの検証で得られたページのソースコードが示す、コメントのhtml構造を取ってこようとしてもうまく値を取ってくることが出来ません。これの原因は何なのでしょうか?
python
1import urllib.request 2from bs4 import BeautifulSoup 3 4def get_yahoo_news(): 5 # ヘッドラインニュースのタイトル格納用リスト 6 news_data = [] 7 8 # urlの指定 9 url = 'http://www.yahoo.co.jp/' 10 11 # ユーザーエージェントを指定?? 12 ua = '' 13 14 req = urllib.request.Request(url, headers={'User-Agent': ua}) 15 16 #htmlの取得 17 html = urllib.request.urlopen(req) 18 19 # htmlパース 20 soup = BeautifulSoup(html, "html.parser") 21 topicsindex = soup.find('div', attrs={'class': 'topicsindex'}) 22 23 24 for li in topicsindex.find_all('li'): 25 a = li.find('a') 26 # 記事タイトルとURLを保存 27 news_data.append([a.contents[0], a.get('href')]) 28 29 return news_data 30 31def main(): 32 # Yahooトップのトピック記事タイトルを取得 33 news_data = get_yahoo_news() 34 35 # 取得データの表示 36 37 carelist = [] 38 39 for news in news_data: 40 if "女性" in news[0]: 41 carelist.append(news) 42 43 print(carelist) 44 45 comment = [] 46 47 48 for carenews in carelist: 49 50 url = carenews[1] 51 ua = '' 52 53 req = urllib.request.Request(url, headers={'User-Agent': ua}) 54 55 #htmlの取得 56 html = urllib.request.urlopen(req) 57 58 # htmlパース 59 soup = BeautifulSoup(html, "html.parser") 60 topicsindex = soup.find("span", attrs={"class":"cmtBody"}) 61 62 63 64 print(topicsindex) 65 66 67 68if __name__ == '__main__': 69 main() 70 71
特に該当の部分を抜粋すると以下のようになります。
python
1 soup = BeautifulSoup(html, "html.parser") 2 topicsindex = soup.find("span", attrs={"class":"cmtBody"})
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/03/28 15:45