【Pythonコード公開】ニュースサイト記事を検索、結果を出力
Python勉強中です。仕事上使えそうだったので、Pythonでニュースサイトから特定の記事を検索して、タイトルとURLを引っ張ってくるコードを作成しました。スクレイピングというやつのです。改善点があれば教えていただけると嬉しいです。
URLとかは架空のものにしています。
使っているモジュールはrequestsとBeautifulSoupです。
#coding: utf-8 from bs4 import BeautifulSoup import requests import csv #ターゲットとなる文言を設定(適宜追加) target1 = "otp" target2 = "Otp" #ターゲットとなるHPのhtmlを取ってくる(適宜追加) res1 = requests.get("https://www.otp_no_blog") res2 = requests.get("https://www.otp_no_blog/otp_no_code") #404などのエラーが出た際は中止 res1.raise_for_status() res2.raise_for_status() #beautiulsoupで解析する soup1 = BeautifulSoup(res1.text, "html.parser") soup2 = BeautifulSoup(res2.text, "html.parser") #Chromeのdeveloper toolでHPとにらめっこして、それっぽいclassを取り出す topics1 = soup1.select(".gs-c-promo-heading") topics2 = soup2.select(".title-link") topics = topics1 + topics2 #さらに、タイトルとURLを取り出す newslist = [] for topic in topics: newslist.append(unicode(topic.getText())) newslist.append(unicode(topic.get("href"))) #unicode-escapeをしないと、この後の作業で”/2018”のようなunicodeに対して、in関数のエラーが出る newslist2 = [] for a in newslist: b = a.encode("unicode-escape") newslist2.append(b) #いよいよ検索 target_news = [] for news_index,news_title in enumerate(newslist2): if target1 in news_title: target_news.append(news_title) target_news.append("https://www.bbc.com" + newslist2[news_index+1]) elif target2 in news_title: target_news.append(news_title) target_news.append("https://www.bbc.com" + newslist2[news_index+1]) #なんか変なものが混ざっていたので整形 target_news2 = [] for elem in target_news: target_news2.append(elem.strip("\\n\\n")) #最後に出力 with open('news.csv', 'w') as csvFile: writer = csv.writer(csvFile) writer.writerow(target_news2)
とはいえ、これだけではまだ使い物にならなそう・・・
更新日時指定とか入れないと。
参考にしたHP(非常にわかりやすかった)
tonari-it.com