2021年に作ったコードがAmeba側の仕様変更で動かなくなったので修正。

修正部分は太字の3行。accountIDとPasswordに各々のIDとパスワードを書いておく必要がある。

50秒待機としているのは、ここで「○○を全てクリックして下さい」等のロボットチェックが入るためである。ここは手動で突破する必要がある。

既知の問題はそのままである(上のブログを参照)。

 

import time
import calendar
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
#年月を指定
year=2024
month=7

days=calendar.monthrange(year, month)[1]#当該月の日数取得
if(month<10):
    month="0"+str(month)

options = webdriver.ChromeOptions()
#ブラウザを表示させる場合、以下をコメントアウト
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)

wait = WebDriverWait(driver, 10)
filename='tmp'+str(year)+str(month)+'.txt'
f=open(filename,mode='a')
URL='https://auth.user.ameba.jp/signin'
driver.get(URL)

driver.find_element_by_name('accountId').send_keys("aaaa@aaa.com")#ID
driver.find_element_by_name('password').send_keys("pppp")#Password

driver.find_element(By.CLASS_NAME,'pp-signin__button--fitted').click()#ログインを押す
time.sleep(50)

for day in range(1,days+1):
    URL='https://blog.ameba.jp/ucs/analysis/analysis_page.do?unit=specific_day&date='+str(year)+str(month)+str(day)
    driver.get(URL)
    element = wait.until(EC.visibility_of_all_elements_located)
    elem=list()
    time.sleep(3)

    try:
        #アクセスのあるページが50ページ以上ある場合、「もっと見る」と出るので押す
        morelink=driver.find_element_by_class_name("p-accessGraph__moreLinkBtn")
        morelink.click()
        time.sleep(3)
    except NoSuchElementException:
        pass

    elem=driver.find_elements_by_class_name("p-accessGraphItem__link")
    count=-1
    for i in elem:
        count+=1
        link=elem[count].get_attribute("href")
        f.write(str(year)+'/'+str(month)+'/'+str(day)+","+elem[count].text+" ,"+link+"  \n")
f.close()
driver.quit()

#以下、出力ファイルの整形
with open(filename, encoding="cp932") as f:
    data_lines = f.read()

data_lines = data_lines.replace("\n", ",")
data_lines = data_lines.replace("html  ,", "html\n")
#保存
filename2=str(year)+str(month)+'.csv'
with open(filename2, mode="w", encoding="cp932") as f:
    f.write(data_lines)