連載企画更新。
前回はこちら。
データベースへの格納はいつでもできるので、とりあえず前半の完成版として投稿します。
Xpathの安定性をしばらく見てみたいと思います。
とりあえず社説を抜いてくるseleniumプログラム
import datetime
from selenium import webdriver #seleniumをインポート
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome import service as fs
import time
def get_toaru_shinbun(dt_today):
chrome_service = fs.Service(executable_path='./chromedriver')
driver = webdriver.Chrome(service=chrome_service)
# chromeドライバーを指定
driver.implicitly_wait(10)
# 待機時間10秒
target_file = "./toaru_shinbun/" + dt_today + "_toaru_shinbun.csv"
f = open(target_file, 'w')
f.write(dt_today)
f.write("\n")
f.write("toaru_shinbun")
f.write("\n")
driver.get('https://www.toaru_shinbun/editorial/')
article_list = driver.find_element(By.XPATH,"/html/body/div/article[1]")
latest_url = article_list.find_element(By.XPATH, 'div/h2/a')
print(latest_url.get_attribute("href"))
latest_url = latest_url.get_attribute("href")
time.sleep(3)
#latest_url.click()
driver.close()
chrome_service = fs.Service(executable_path='./chromedriver')
driver = webdriver.Chrome(service=chrome_service) # chromeドライバーを指定
driver.implicitly_wait(10) # 待機時間10秒
driver.get(latest_url)
article_title = driver.find_element(By.XPATH,'/html/body/div/h1')
f.write(article_title.text)
f.write("\n")
#print(article_title.text)
article_body = driver.find_element(By.XPATH,'/html/body/article')
articles = article_body.find_elements(By.XPATH, 'p')
for p_body in articles:
f.write(p_body.text)
f.write("\n")
#print(p_body.text)
driver.close()
return
if __name__ == '__main__':
dt_today = datetime.date.today().strftime('%Y%m%d')
try:
get_toaru_shinbun(dt_today)
except Exception as e:
print(e)
以前との改善点
新聞社ごとに関数化
get_xxx の部分で新聞社ごとの取得部を関数化してます。
機能として明確に分離しています。
新聞は架空のものを使ってますので、マネしたい方はXpathを変更してください。
get_xxx内部のdriver.getを開いて閉じるようにした
driver.clickでページ遷移していた部分を、いったんdriver.closeするようにした。
理由として、driver.clickで遷移しようとすると、広告の関係かクリックURLと違うURLにアクセスしたことになってエラーになったため。