SeleniumでCookie情報をrequestsに渡しMP3をダウンロード(Alpha)

投稿者: | 2023-12-02

#SeleniumでCookie情報をrequestsに渡しMP3をダウンロード(Alpha)



from selenium import webdriver
import requests, os, time, json
from bs4 import BeautifulSoup
import pathlib

# 初期設定
driver_path = "/Users/mbp441/Desktop/github/PYTHON/chromedriver"

MP3_URL = 'https://alpha.japantimes.co.jp/clubalpha/readout/'
LOGIN_ID = ""
LOGIN_PW = "”

## 基本パターン(ログイン〜ログイン後の画面まで)

driver = webdriver.Chrome(driver_path)
driver.get(MP3_URL)
time.sleep(3)

# ログインボタンクリック(デベロップモードでは「.」が見えてない)
driver.find_element(By.CLASS_NAME, "el_btn.el_btn__red.js_modal_btn.js_matchHeight02").click()

elem_id = driver.find_element(By.ID, "js-pwEmail")
elem_pw = driver.find_element(By.ID, "js-pwPassword")

elem_id.clear()
elem_id.send_keys(LOGIN_ID)
elem_pw.clear()
elem_pw.send_keys(LOGIN_PW)

elem_login = driver.find_element(By.ID, "js-pwLoginBtn")
elem_login.click()
time.sleep(3)

# 前の号を見る+をクリックさせて内容を増す場合

#前の号は末尾の[]が3、4、5の順
# /html/body/div[1]/div[3]/section[2]/div[3]/a
# /html/body/div[1]/div[3]/section[2]/div[4]/a
# /html/body/div[1]/div[3]/section[2]/div[5]/a

def view_previous(num):
    for i in range(num):
        cnt = i + 3
        print(cnt)
        driver.find_element(By.XPATH, f"/html/body/div[1]/div[3]/section[2]/div[{cnt}]/a").click()
        print(f"「前の号を見る」をクリックしました。")
        time.sleep(5)

cnt = int(input("前の号も含める場合は1、それ以前のものはさらに+1を入力:"))
view_previous(2)

# 音声ファイルのタイトル、リンク先(URL)等を取得する
elem_ttls = driver.find_elements(By.CLASS_NAME,"bl_soundList_ttl")
elem_links = driver.find_elements(By.CSS_SELECTOR, "div.bl_soundList_file > a")

base_dir = pathlib.Path('/Users/mbp441/Desktop/Alpha_MP3')

mp3_data = []

for ttl, link in zip(elem_ttls, elem_links):
    link = link.get_attribute('href')
    filename = link[link.rfind('/') + 1:]
    title = filename[:10] + "_" + ttl.text
    file_path = base_dir / filename
    
    print(filename)
    print(title)
    print(link)
    print(f'保存:{file_path}')
    print('-'*40)
    
    mp3_data.append({
            'file': file_path,
            'link': link,
        })

## めちゃくちゃ感動 以下。

# ファイルのダウンロードはrequestsにまかせるため、SeleからrequestsにCookiesを渡して対応する
# Seleniumでログイン認証後のCookiesを取得する

cookies = {c['name']: c['value'] for c in driver.get_cookies()}

# requestsを使って、ファイルDLも With Open でバイナリモードで1回ずつ保存できる

def download_to_file(url, file):
    print('download:', url)
    bin = requests.get(url, cookies=cookies).content
    time.sleep(2)
    with open(file, 'wb') as fp:
        fp.write(bin)

for i in mp3_data:
    download_to_file(i['link'], i['file'])

driver.quit()