Pythonでやってみよ。記事一覧の取得のつづき
ダッシュボードのコメント数推移をつくるのにseleniumを使って思いました。自分の記事一覧の取得は、スケルトンライナーを実行するたびに全部取得するので、時間がかかるようになります。以前に取得していた分まで取得するので、効率もよくありません。そこで、「指定日時以降分」だけ取得できるように考えてやってみました。
いろいろ試行錯誤してできました。
ただ、seleniumを使うスケルトンライナーにすると長くなりすぎ感が否めないので、自作関数(def)を作ってみました。
#使い方vv
#pythonでBeautifulSoupでnoteの記事一覧取得する方法vv
>>> z_=get_note_articlelist(dy_='202507280000',tt_=10)
$ pn -c "$imt;z_=get_note_articlelist(dy_='202507280000',tt_=10)"
#--- 2025-07-07 13:58:50 +0900 ---
追加(htmlのソースをコピーするのではなく、seleniumで取得する版)
#--- 2025-07-30 22:55:19 +0900 ---
追加(htmlのソースをコピーするのではなく、seleniumで取得する版のdef版)
--- 2025-07-31 14:41:51 +0900 ---
こちらが、自作関数です。
def get_note_articlelist(url='https://note.com/coding_kiwi',dwd='~/Downloads/note_codingkiwi2/',f_='notecom_codingkiwi',dy_='202505200000',tt_=10):
'''
seleniumでwebから記事を取得して保存(firefox版)
'''
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
#Seleniumをあらゆる環境で起動させるChromeオプション
options=Options()
options.add_argument('--disable-gpu')
options.add_argument('--disable-extensions')
options.add_argument('--start-maximized')
options.add_argument('--kiosk')
#Optionでヘッドレスモードを指定
options.add_argument('--headless')
DRIVER_PATH='/usr/local/bin/geckodriver'
options.binary_location='/usr/bin/firefox'
#WebDriverをオプションを設定して起動
driver=webdriver.Firefox(options=options)
#指定している要素が表示されるまでの待ち時間(秒)
#ページの切り替わり等で要素が表示されるまで自動的に待ってくれる
driver.implicitly_wait(tt_)
driver.get(url)
time.sleep(5)
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
time.sleep(1)
exec("while True:\n button=driver.find_elements(By.XPATH,'//*[@id=\":R1b69uukpuujquckq:\"]')\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight)\");time.sleep(1)\n if button:button[0].click();time.sleep(1)\n else:break\nelse:print('ok')")
driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
time.sleep(5)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
time.sleep(5)
html_=driver.find_element(By.TAG_NAME,'html').get_attribute('outerHTML')
driver.quit()
rt=BeautifulSoup(html_,'lxml')
ans_=[[x+''+z.strftime('%Y%m%d%H%M')+'.txt',subp.run(['w3m','-s','-dump','-cols','2000',y],capture_output=True,encoding='utf-8').stdout] for x,y,z in sorted([x for x in list(set([(x.a.get('title'),x.a.get('href'),datetime.datetime.strptime(re.sub(':','',x.time.get('datetime')),'%Y-%m-%dT%H%M%S%z').astimezone()) for x in rt.find_all('div',class=re.compile('flex w-full rounded-lg bg-surface-normal'))])) if x[-1]>datetime.datetime.strptime(dy_,'%Y%m%d%H%M').astimezone()],key=lambda x:x[-1])]
exec("for x in ans_:fw(str(pathlib.Path(dwd).expanduser())+'/'+f_+'_'+x[0],x[1]);time.sleep(3)")
return
下のは自作関数にする前にスケルトンライナーでやってみた版です。長いし、試行錯誤しているので処理も冗長なところがありますね。しかも、指定日時以降にはなってなくて、全取得です。でもこうやって試行錯誤しておくと、結果までの筋道がつくので考え方ややり方が整理されるというメリットがありますよ。
#使い方vv
#pythonでBeautifulSoupでnoteの記事一覧取得する方法vv
>>> url_='https://note.com/coding_kiwi';driver,titile_,html_,rt=selenium_fox_pre(url_);from selenium.webdriver.common.by import By;exec("while True:\n button=driver.find_elements(By.XPATH,'//*[@id=\":R1b69uukpuujquckq:\"]')\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight)\");time.sleep(1)\n if button:button[0].click();time.sleep(1)\n else:break\nelse:print('ok')");driver.execute_script("window.scrollTo(0, document.body.scrollHeight)");time.sleep(5);driver.execute_script("window.scrollTo(0, document.body.scrollHeight)");time.sleep(5);html_=driver.find_element(By.TAG_NAME,'html').get_attribute('outerHTML');driver.quit();rt=BeautifulSoup(html_,'lxml');d_=list(set([x.get('href') for x in rt.find_all('a') if x.get('title')!=None]))[::-1];a_=[BeautifulSoup(requests.get(x).text,'lxml') for x in d_];t_=[x.find('h1',class_='o-noteContentHeader__title').text.strip() for x in a_];t1_=[x.time.text.strip() for x in a_];z_=[subp.run(['w3m','-s','-dump','-cols','2000',x],capture_output=True,encoding='utf-8').stdout for x in d_];ans_=[w+'\t'+datetime.datetime.strptime((x),'%Y年%m月%d日 %H:%M').strftime('%Y%m%d%H%M')+'\t'+y+'\n'+z for w,x,y,z in zip(t_,t1_,d_,z_)];ans_=sorted(ans_,key=lambda x:x.split('\t')[1]);pr_joinn(ans_);exec("for x in ans_:fw(str(pathlib.Path('~/Downloads/note_codingkiwi1/').expanduser())+'/notecom_codingkiwi'+''+x.split('\t')[0]+''+x.split('\t')[1]+'.txt',x.split('\t')[-1]);time.sleep(3)")
$ pn -c "$imt;url_='https://note.com/coding_kiwi';driver,titile_,html_,rt=selenium_fox_pre(url_);from selenium.webdriver.common.by import By;exec(\"while True:\\n button=driver.find_elements(By.XPATH,'//*[@id=\\\":R1b69uukpuujquckq:\\\"]')\\n driver.execute_script(\\\"window.scrollTo(0, document.body.scrollHeight)\\\");time.sleep(1)\\n if button:button[0].click();time.sleep(1)\\n else:break\\nelse:print('ok')\");driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight)\");time.sleep(5);driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight)\");time.sleep(5);html_=driver.find_element(By.TAG_NAME,'html').get_attribute('outerHTML');driver.quit();rt=BeautifulSoup(html_,'lxml');d_=list(set([x.get('href') for x in rt.find_all('a') if x.get('title')!=None]))[::-1];a_=[BeautifulSoup(requests.get(x).text,'lxml') for x in d_];t_=[x.find('h1',class_='o-noteContentHeader__title').text.strip() for x in a_];t1_=[x.time.text.strip() for x in a_];z_=[subp.run(['w3m','-s','-dump','-cols','2000',x],capture_output=True,encoding='utf-8').stdout for x in d_];ans_=[w+'\\t'+datetime.datetime.strptime((x),'%Y年%m月%d日 %H:%M').strftime('%Y%m%d%H%M')+'\\t'+y+'\\n'+z for w,x,y,z in zip(t_,t1_,d_,z_)];ans_=sorted(ans_,key=lambda x:x.split('\\t')[1]);pr_joinn(ans_);exec(\"for x in ans_:fw(str(pathlib.Path('~/Downloads/note_codingkiwi1/').expanduser())+'/notecom_codingkiwi'+''+x.split('\\t')[0]+''+x.split('\\t')[1]+'.txt',x.split('\\t')[-1]);time.sleep(3)\")"
#--- 2025-07-07 13:58:50 +0900 ---
追加(htmlのソースをコピーするのではなく、seleniumで取得する版)
--- 2025-07-30 22:55:19 +0900 ---
