1636198980
Webスクレイピングとは、Webサイトからデータを抽出することです。これはコピーの形式であり、特定のデータが収集され、後で分析または取得するためにWebから中央のローカルデータベースまたはスプレッドシートにコピーされます。
以来YouTubeはインターネットで最大の動画共有サイトで、そこからデータを抽出することは好き、嫌いとはるかにビデオや意見を記録し、チャンネルの人気に追跡する、あなたが最も人気のあるチャンネルを見つけることができ、非常に役立ちます。このチュートリアルでは、Pythonでrequests_htmlとBeautifulSoupを使用してYouTube動画からデータを抽出する方法を学習します。
この方法を使用してYouTubeデータを抽出することは信頼できないことに注意してください。これは、YouTubeがコードを変更し続けるため、コードがいつでも機能しないためです。したがって、より信頼性の高い使用のために、代わりにYouTubeAPIを使用してデータを抽出することをお勧めします。
必要な依存関係のインストール:
pip3 install requests_html bs4
クイックスクリプトに飛び込む前に、BeautifulSoupを使用してWebサイトからそのようなデータを抽出する方法を実験し、Pythonインタラクティブシェルを開いて、次のコード行を記述する必要があります。
from requests_html import HTMLSession
from bs4 import BeautifulSoup as bs # importing BeautifulSoup
# sample youtube video url
video_url = "https://www.youtube.com/watch?v=jNQXAC9IVRw"
# init an HTML Session
session = HTMLSession()
# get the html content
response = session.get(video_url)
# execute Java-script
response.html.render(sleep=1)
# create bs object to parse HTML
soup = bs(response.html.html, "html.parser")
これにより、そのYouTubeビデオURLにリクエストが送信され、Javascriptがレンダリングされ、最後に、結果のHTMLをラップするBeatifulSoupオブジェクトが作成されます。
では、ページ内のすべてのメタタグを見つけてみましょう。
In [10]: soup.find_all("meta")
Out[10]:
[<meta content="IE=edge" http-equiv="X-UA-Compatible"/>,
<meta content="rgba(255,255,255,0.98)" name="theme-color"/>,
<meta content="Me at the zoo" name="title"/>,
<meta content="The first video on YouTube. While you wait for Part 2, listen to this great song: https://www.youtube.com/watch?v=zj82_v2R6ts" name="description"/>,
<meta content="me at the zoo, jawed karim, first youtube video" name="keywords"/>,
<meta content="YouTube" property="og:site_name"/>,
<meta content="https://www.youtube.com/watch?v=jNQXAC9IVRw" property="og:url"/>,
<meta content="Me at the zoo" property="og:title"/>,
<meta content="https://i.ytimg.com/vi/jNQXAC9IVRw/hqdefault.jpg" property="og:image"/>,
<meta content="480" property="og:image:width"/>,
<meta content="360" property="og:image:height"/>,
<meta content="The first video on YouTube. While you wait for Part 2, listen to this great song: https://www.youtube.com/watch?v=zj82_v2R6ts" property="og:description"/>,
<meta content="544007664" property="al:ios:app_store_id"/>,
<meta content="YouTube" property="al:ios:app_name"/>,
<meta content="vnd.youtube://www.youtube.com/watch?v=jNQXAC9IVRw&feature=applinks" property="al:ios:url"/>,
<meta content="vnd.youtube://www.youtube.com/watch?v=jNQXAC9IVRw&feature=applinks" property="al:android:url"/>,
<meta content="http://www.youtube.com/watch?v=jNQXAC9IVRw&feature=applinks" property="al:web:url"/>,
<meta content="video.other" property="og:type"/>,
<meta content="https://www.youtube.com/embed/jNQXAC9IVRw" property="og:video:url"/>,
<meta content="https://www.youtube.com/embed/jNQXAC9IVRw" property="og:video:secure_url"/>,
<meta content="text/html" property="og:video:type"/>,
<meta content="480" property="og:video:width"/>,
<meta content="360" property="og:video:height"/>,
<meta content="YouTube" property="al:android:app_name"/>,
<meta content="com.google.android.youtube" property="al:android:package"/>,
<meta content="me at the zoo" property="og:video:tag"/>,
<meta content="jawed karim" property="og:video:tag"/>,
<meta content="first youtube video" property="og:video:tag"/>,
<meta content="87741124305" property="fb:app_id"/>,
<meta content="player" name="twitter:card"/>,
<meta content="@youtube" name="twitter:site"/>,
<meta content="https://www.youtube.com/watch?v=jNQXAC9IVRw" name="twitter:url"/>,
<meta content="Me at the zoo" name="twitter:title"/>,
<meta content="The first video on YouTube. While you wait for Part 2, listen to this great song: https://www.youtube.com/watch?v=zj82_v2R6ts" name="twitter:description"/>,
<meta content="https://i.ytimg.com/vi/jNQXAC9IVRw/hqdefault.jpg" name="twitter:image"/>,
<meta content="YouTube" name="twitter:app:name:iphone"/>,
<meta content="544007664" name="twitter:app:id:iphone"/>,
<meta content="YouTube" name="twitter:app:name:ipad"/>,
<meta content="544007664" name="twitter:app:id:ipad"/>,
<meta content="vnd.youtube://www.youtube.com/watch?v=jNQXAC9IVRw&feature=applinks" name="twitter:app:url:iphone"/>,
<meta content="vnd.youtube://www.youtube.com/watch?v=jNQXAC9IVRw&feature=applinks" name="twitter:app:url:ipad"/>,
<meta content="YouTube" name="twitter:app:name:googleplay"/>,
<meta content="com.google.android.youtube" name="twitter:app:id:googleplay"/>,
<meta content="https://www.youtube.com/watch?v=jNQXAC9IVRw" name="twitter:app:url:googleplay"/>,
<meta content="https://www.youtube.com/embed/jNQXAC9IVRw" name="twitter:player"/>,
<meta content="480" name="twitter:player:width"/>,
<meta content="360" name="twitter:player:height"/>,
<meta content="Me at the zoo" itemprop="name"/>,
<meta content="The first video on YouTube. While you wait for Part 2, listen to this great song: https://www.youtube.com/watch?v=zj82_v2R6ts" itemprop="description"/>,
<meta content="False" itemprop="paid"/>,
<meta content="UC4QobU6STFB0P71PMvOGN5A" itemprop="channelId"/>,
<meta content="jNQXAC9IVRw" itemprop="videoId"/>,
<meta content="PT0M19S" itemprop="duration"/>,
<meta content="False" itemprop="unlisted"/>,
<meta content="480" itemprop="width"/>,
<meta content="360" itemprop="height"/>,
<meta content="HTML5 Flash" itemprop="playerType"/>,
<meta content="480" itemprop="width"/>,
<meta content="360" itemprop="height"/>,
<meta content="true" itemprop="isFamilyFriendly"/>,
<meta content="AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GS,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TK,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW" itemprop="regionsAllowed"/>,
<meta content="172826227" itemprop="interactionCount"/>,
<meta content="2005-04-23" itemprop="datePublished"/>,
<meta content="2005-04-23" itemprop="uploadDate"/>,
<meta content="Film & Animation" itemprop="genre"/>]
そのように簡単で、ここにはたくさんの有用なデータがあります。たとえば、次の方法でビデオタイトルを取得できます。
In [11]: soup.find("meta", itemprop="name")["content"]
Out[11]: 'Me at the zoo'
またはビューの数:
In [12]: soup.find("meta", itemprop="interactionCount")['content']
Out[12]: '172826227'
このように、あなたはそのウェブページからあなたが望むすべてを抽出することができるでしょう。それでは、YouTubeビデオページから取得できるいくつかの有用な情報を抽出するスクリプトを作成し、新しいPythonファイルを開いて、次の手順を実行してみましょう。
必要なモジュールのインポート:
from requests_html import HTMLSession
from bs4 import BeautifulSoup as bs
すべてのビデオデータを抽出する関数を作成する前に、HTTPセッションを初期化しましょう。
# init session
session = HTMLSession()
YouTubeビデオのURLを指定して、辞書内のすべてのデータを返す関数を作成しましょう。
def get_video_info(url):
# download HTML code
response = session.get(url)
# execute Javascript
response.html.render(sleep=1)
# create beautiful soup object to parse HTML
soup = bs(response.html.html, "html.parser")
# open("index.html", "w").write(response.html.html)
# initialize the result
result = {}
WebページのHTMLコンテンツをダウンロードした後、render()
メソッドを実行してJavascriptを実行し、探しているデータがHTMLでレンダリングされるようにしました。
タイムアウトエラーが発生した場合は、timeout
パラメータを追加して60秒(デフォルトは8秒)などに設定するだけでよいことに注意してください。
response.html.render(sleep=1, timeout=60)
ビデオタイトルの取得:
# video title
result["title"] = soup.find("meta", itemprop="name")['content']
整数に変換されたビューの数:
# video views (converted to integer)
result["views"] = result["views"] = soup.find("meta", itemprop="interactionCount")['content']
ビデオの説明を取得します。
# video description
result["description"] = soup.find("meta", itemprop="description")['content']
ビデオが公開された日付:
# date published
result["date_published"] = soup.find("meta", itemprop="datePublished")['content']
ビデオの長さ:
# get the duration of the video
result["duration"] = soup.find("span", {"class": "ytp-time-duration"}).text
前のフィールドとしてメタタグから期間を取得することもできますが、PT0M19S
19秒に変換されるような別の形式、またはタグ00:19
内の形式になりますytp-time-duration
span
。
ビデオタグを抽出することもできます。
# get the video tags
result["tags"] = ', '.join([ meta.attrs.get("content") for meta in soup.find_all("meta", {"property": "og:video:tag"}) ])
整数としての好き嫌いの数:
# number of likes
text_yt_formatted_strings = soup.find_all("yt-formatted-string", {"id": "text", "class": "ytd-toggle-button-renderer"})
result["likes"] = ''.join([ c for c in text_yt_formatted_strings[0].attrs.get("aria-label") if c.isdigit() ])
result["likes"] = 0 if result['likes'] == '' else int(result['likes'])
# number of dislikes
result["dislikes"] = ''.join([ c for c in text_yt_formatted_strings[1].attrs.get("aria-label") if c.isdigit() ])
result['dislikes'] = 0 if result['dislikes'] == '' else int(result['dislikes'])
YouTubeビデオでは、名前やチャンネル登録者数などのチャンネルの詳細を確認できるので、それも取得しましょう。
# channel details
channel_tag = soup.find("yt-formatted-string", {"class": "ytd-channel-name"}).find("a")
# channel name
channel_name = channel_tag.text
# channel URL
channel_url = f"https://www.youtube.com{channel_tag['href']}"
# number of subscribers as str
channel_subscribers = soup.find("yt-formatted-string", {"id": "owner-sub-count"}).text.strip()
result['channel'] = {'name': channel_name, 'url': channel_url, 'subscribers': channel_subscribers}
return result
以来soup.find()関数が返すタグオブジェクトを、あなたはまだ他のタグ内のHTMLタグを見つけることができます。その結果、find()を複数回呼び出すのが一般的な方法です。
これで、この関数は辞書に多くのビデオ情報を返します。スクリプトを完成させましょう。
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="YouTube Video Data Extractor")
parser.add_argument("url", help="URL of the YouTube video")
args = parser.parse_args()
url = args.url
# get the data
data = get_video_info(url)
# print in nice format
print(f"Title: {data['title']}")
print(f"Views: {data['views']}")
print(f"Published at: {data['date_published']}")
print(f"Video Duration: {data['duration']}")
print(f"Video tags: {data['tags']}")
print(f"Likes: {data['likes']}")
print(f"Dislikes: {data['dislikes']}")
print(f"\nDescription: {data['description']}\n")
print(f"\nChannel Name: {data['channel']['name']}")
print(f"Channel URL: {data['channel']['url']}")
print(f"Channel Subscribers: {data['channel']['subscribers']}")
ここでは特別なことは何もありません。コマンドラインからビデオのURLを取得する方法が必要なので、上記はそれを実行し、フォーマットで出力します。スクリプトを実行したときの出力は次のとおりです。
C:\youtube-extractor>python extract_video_info.py https://www.youtube.com/watch?v=jNQXAC9IVRw
Title: Me at the zoo
Views: 172639597
Published at: 2005-04-23
Video Duration: 0:18
Video tags: me at the zoo, jawed karim, first youtube video
Likes: 8188077
Dislikes: 191986
Description: The first video on YouTube. While you wait for Part 2, listen to this great song: https://www.youtube.com/watch?v=zj82_v2R6ts
Channel Name: jawed
Channel URL: https://www.youtube.com/channel/UC4QobU6STFB0P71PMvOGN5A
Channel Subscribers: 1.98M subscribers
これです!HTMLタグからデータを抽出してから、ビデオ品質などの他のフィールドを追加する方法を知っています。
YouTubeのコメントを抽出したい場合は、これ以外にもやるべきことがたくさんあります。これには別のチュートリアルがあります。
YouTubeビデオの詳細を抽出できるだけでなく、このスキルを任意のWebサイトに適用することもできます。ウィキペディアのページを抽出したい場合は、そのためのチュートリアルがあります!それとも、Googleから気象データを取得したいですか?そのためのチュートリアルもあります。
このチュートリアルの完全なコードをここで確認してください。
リンク: https://www.thepythoncode.com/article/get-youtube-data-python
1636198980
Webスクレイピングとは、Webサイトからデータを抽出することです。これはコピーの形式であり、特定のデータが収集され、後で分析または取得するためにWebから中央のローカルデータベースまたはスプレッドシートにコピーされます。
以来YouTubeはインターネットで最大の動画共有サイトで、そこからデータを抽出することは好き、嫌いとはるかにビデオや意見を記録し、チャンネルの人気に追跡する、あなたが最も人気のあるチャンネルを見つけることができ、非常に役立ちます。このチュートリアルでは、Pythonでrequests_htmlとBeautifulSoupを使用してYouTube動画からデータを抽出する方法を学習します。
この方法を使用してYouTubeデータを抽出することは信頼できないことに注意してください。これは、YouTubeがコードを変更し続けるため、コードがいつでも機能しないためです。したがって、より信頼性の高い使用のために、代わりにYouTubeAPIを使用してデータを抽出することをお勧めします。
必要な依存関係のインストール:
pip3 install requests_html bs4
クイックスクリプトに飛び込む前に、BeautifulSoupを使用してWebサイトからそのようなデータを抽出する方法を実験し、Pythonインタラクティブシェルを開いて、次のコード行を記述する必要があります。
from requests_html import HTMLSession
from bs4 import BeautifulSoup as bs # importing BeautifulSoup
# sample youtube video url
video_url = "https://www.youtube.com/watch?v=jNQXAC9IVRw"
# init an HTML Session
session = HTMLSession()
# get the html content
response = session.get(video_url)
# execute Java-script
response.html.render(sleep=1)
# create bs object to parse HTML
soup = bs(response.html.html, "html.parser")
これにより、そのYouTubeビデオURLにリクエストが送信され、Javascriptがレンダリングされ、最後に、結果のHTMLをラップするBeatifulSoupオブジェクトが作成されます。
では、ページ内のすべてのメタタグを見つけてみましょう。
In [10]: soup.find_all("meta")
Out[10]:
[<meta content="IE=edge" http-equiv="X-UA-Compatible"/>,
<meta content="rgba(255,255,255,0.98)" name="theme-color"/>,
<meta content="Me at the zoo" name="title"/>,
<meta content="The first video on YouTube. While you wait for Part 2, listen to this great song: https://www.youtube.com/watch?v=zj82_v2R6ts" name="description"/>,
<meta content="me at the zoo, jawed karim, first youtube video" name="keywords"/>,
<meta content="YouTube" property="og:site_name"/>,
<meta content="https://www.youtube.com/watch?v=jNQXAC9IVRw" property="og:url"/>,
<meta content="Me at the zoo" property="og:title"/>,
<meta content="https://i.ytimg.com/vi/jNQXAC9IVRw/hqdefault.jpg" property="og:image"/>,
<meta content="480" property="og:image:width"/>,
<meta content="360" property="og:image:height"/>,
<meta content="The first video on YouTube. While you wait for Part 2, listen to this great song: https://www.youtube.com/watch?v=zj82_v2R6ts" property="og:description"/>,
<meta content="544007664" property="al:ios:app_store_id"/>,
<meta content="YouTube" property="al:ios:app_name"/>,
<meta content="vnd.youtube://www.youtube.com/watch?v=jNQXAC9IVRw&feature=applinks" property="al:ios:url"/>,
<meta content="vnd.youtube://www.youtube.com/watch?v=jNQXAC9IVRw&feature=applinks" property="al:android:url"/>,
<meta content="http://www.youtube.com/watch?v=jNQXAC9IVRw&feature=applinks" property="al:web:url"/>,
<meta content="video.other" property="og:type"/>,
<meta content="https://www.youtube.com/embed/jNQXAC9IVRw" property="og:video:url"/>,
<meta content="https://www.youtube.com/embed/jNQXAC9IVRw" property="og:video:secure_url"/>,
<meta content="text/html" property="og:video:type"/>,
<meta content="480" property="og:video:width"/>,
<meta content="360" property="og:video:height"/>,
<meta content="YouTube" property="al:android:app_name"/>,
<meta content="com.google.android.youtube" property="al:android:package"/>,
<meta content="me at the zoo" property="og:video:tag"/>,
<meta content="jawed karim" property="og:video:tag"/>,
<meta content="first youtube video" property="og:video:tag"/>,
<meta content="87741124305" property="fb:app_id"/>,
<meta content="player" name="twitter:card"/>,
<meta content="@youtube" name="twitter:site"/>,
<meta content="https://www.youtube.com/watch?v=jNQXAC9IVRw" name="twitter:url"/>,
<meta content="Me at the zoo" name="twitter:title"/>,
<meta content="The first video on YouTube. While you wait for Part 2, listen to this great song: https://www.youtube.com/watch?v=zj82_v2R6ts" name="twitter:description"/>,
<meta content="https://i.ytimg.com/vi/jNQXAC9IVRw/hqdefault.jpg" name="twitter:image"/>,
<meta content="YouTube" name="twitter:app:name:iphone"/>,
<meta content="544007664" name="twitter:app:id:iphone"/>,
<meta content="YouTube" name="twitter:app:name:ipad"/>,
<meta content="544007664" name="twitter:app:id:ipad"/>,
<meta content="vnd.youtube://www.youtube.com/watch?v=jNQXAC9IVRw&feature=applinks" name="twitter:app:url:iphone"/>,
<meta content="vnd.youtube://www.youtube.com/watch?v=jNQXAC9IVRw&feature=applinks" name="twitter:app:url:ipad"/>,
<meta content="YouTube" name="twitter:app:name:googleplay"/>,
<meta content="com.google.android.youtube" name="twitter:app:id:googleplay"/>,
<meta content="https://www.youtube.com/watch?v=jNQXAC9IVRw" name="twitter:app:url:googleplay"/>,
<meta content="https://www.youtube.com/embed/jNQXAC9IVRw" name="twitter:player"/>,
<meta content="480" name="twitter:player:width"/>,
<meta content="360" name="twitter:player:height"/>,
<meta content="Me at the zoo" itemprop="name"/>,
<meta content="The first video on YouTube. While you wait for Part 2, listen to this great song: https://www.youtube.com/watch?v=zj82_v2R6ts" itemprop="description"/>,
<meta content="False" itemprop="paid"/>,
<meta content="UC4QobU6STFB0P71PMvOGN5A" itemprop="channelId"/>,
<meta content="jNQXAC9IVRw" itemprop="videoId"/>,
<meta content="PT0M19S" itemprop="duration"/>,
<meta content="False" itemprop="unlisted"/>,
<meta content="480" itemprop="width"/>,
<meta content="360" itemprop="height"/>,
<meta content="HTML5 Flash" itemprop="playerType"/>,
<meta content="480" itemprop="width"/>,
<meta content="360" itemprop="height"/>,
<meta content="true" itemprop="isFamilyFriendly"/>,
<meta content="AD,AE,AF,AG,AI,AL,AM,AO,AQ,AR,AS,AT,AU,AW,AX,AZ,BA,BB,BD,BE,BF,BG,BH,BI,BJ,BL,BM,BN,BO,BQ,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CD,CF,CG,CH,CI,CK,CL,CM,CN,CO,CR,CU,CV,CW,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,ES,ET,FI,FJ,FK,FM,FO,FR,GA,GB,GD,GE,GF,GG,GH,GI,GL,GM,GN,GP,GQ,GR,GS,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IM,IN,IO,IQ,IR,IS,IT,JE,JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,LT,LU,LV,LY,MA,MC,MD,ME,MF,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,PH,PK,PL,PM,PN,PR,PS,PT,PW,PY,QA,RE,RO,RS,RU,RW,SA,SB,SC,SD,SE,SG,SH,SI,SJ,SK,SL,SM,SN,SO,SR,SS,ST,SV,SX,SY,SZ,TC,TD,TF,TG,TH,TJ,TK,TL,TM,TN,TO,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,WS,YE,YT,ZA,ZM,ZW" itemprop="regionsAllowed"/>,
<meta content="172826227" itemprop="interactionCount"/>,
<meta content="2005-04-23" itemprop="datePublished"/>,
<meta content="2005-04-23" itemprop="uploadDate"/>,
<meta content="Film & Animation" itemprop="genre"/>]
そのように簡単で、ここにはたくさんの有用なデータがあります。たとえば、次の方法でビデオタイトルを取得できます。
In [11]: soup.find("meta", itemprop="name")["content"]
Out[11]: 'Me at the zoo'
またはビューの数:
In [12]: soup.find("meta", itemprop="interactionCount")['content']
Out[12]: '172826227'
このように、あなたはそのウェブページからあなたが望むすべてを抽出することができるでしょう。それでは、YouTubeビデオページから取得できるいくつかの有用な情報を抽出するスクリプトを作成し、新しいPythonファイルを開いて、次の手順を実行してみましょう。
必要なモジュールのインポート:
from requests_html import HTMLSession
from bs4 import BeautifulSoup as bs
すべてのビデオデータを抽出する関数を作成する前に、HTTPセッションを初期化しましょう。
# init session
session = HTMLSession()
YouTubeビデオのURLを指定して、辞書内のすべてのデータを返す関数を作成しましょう。
def get_video_info(url):
# download HTML code
response = session.get(url)
# execute Javascript
response.html.render(sleep=1)
# create beautiful soup object to parse HTML
soup = bs(response.html.html, "html.parser")
# open("index.html", "w").write(response.html.html)
# initialize the result
result = {}
WebページのHTMLコンテンツをダウンロードした後、render()
メソッドを実行してJavascriptを実行し、探しているデータがHTMLでレンダリングされるようにしました。
タイムアウトエラーが発生した場合は、timeout
パラメータを追加して60秒(デフォルトは8秒)などに設定するだけでよいことに注意してください。
response.html.render(sleep=1, timeout=60)
ビデオタイトルの取得:
# video title
result["title"] = soup.find("meta", itemprop="name")['content']
整数に変換されたビューの数:
# video views (converted to integer)
result["views"] = result["views"] = soup.find("meta", itemprop="interactionCount")['content']
ビデオの説明を取得します。
# video description
result["description"] = soup.find("meta", itemprop="description")['content']
ビデオが公開された日付:
# date published
result["date_published"] = soup.find("meta", itemprop="datePublished")['content']
ビデオの長さ:
# get the duration of the video
result["duration"] = soup.find("span", {"class": "ytp-time-duration"}).text
前のフィールドとしてメタタグから期間を取得することもできますが、PT0M19S
19秒に変換されるような別の形式、またはタグ00:19
内の形式になりますytp-time-duration
span
。
ビデオタグを抽出することもできます。
# get the video tags
result["tags"] = ', '.join([ meta.attrs.get("content") for meta in soup.find_all("meta", {"property": "og:video:tag"}) ])
整数としての好き嫌いの数:
# number of likes
text_yt_formatted_strings = soup.find_all("yt-formatted-string", {"id": "text", "class": "ytd-toggle-button-renderer"})
result["likes"] = ''.join([ c for c in text_yt_formatted_strings[0].attrs.get("aria-label") if c.isdigit() ])
result["likes"] = 0 if result['likes'] == '' else int(result['likes'])
# number of dislikes
result["dislikes"] = ''.join([ c for c in text_yt_formatted_strings[1].attrs.get("aria-label") if c.isdigit() ])
result['dislikes'] = 0 if result['dislikes'] == '' else int(result['dislikes'])
YouTubeビデオでは、名前やチャンネル登録者数などのチャンネルの詳細を確認できるので、それも取得しましょう。
# channel details
channel_tag = soup.find("yt-formatted-string", {"class": "ytd-channel-name"}).find("a")
# channel name
channel_name = channel_tag.text
# channel URL
channel_url = f"https://www.youtube.com{channel_tag['href']}"
# number of subscribers as str
channel_subscribers = soup.find("yt-formatted-string", {"id": "owner-sub-count"}).text.strip()
result['channel'] = {'name': channel_name, 'url': channel_url, 'subscribers': channel_subscribers}
return result
以来soup.find()関数が返すタグオブジェクトを、あなたはまだ他のタグ内のHTMLタグを見つけることができます。その結果、find()を複数回呼び出すのが一般的な方法です。
これで、この関数は辞書に多くのビデオ情報を返します。スクリプトを完成させましょう。
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="YouTube Video Data Extractor")
parser.add_argument("url", help="URL of the YouTube video")
args = parser.parse_args()
url = args.url
# get the data
data = get_video_info(url)
# print in nice format
print(f"Title: {data['title']}")
print(f"Views: {data['views']}")
print(f"Published at: {data['date_published']}")
print(f"Video Duration: {data['duration']}")
print(f"Video tags: {data['tags']}")
print(f"Likes: {data['likes']}")
print(f"Dislikes: {data['dislikes']}")
print(f"\nDescription: {data['description']}\n")
print(f"\nChannel Name: {data['channel']['name']}")
print(f"Channel URL: {data['channel']['url']}")
print(f"Channel Subscribers: {data['channel']['subscribers']}")
ここでは特別なことは何もありません。コマンドラインからビデオのURLを取得する方法が必要なので、上記はそれを実行し、フォーマットで出力します。スクリプトを実行したときの出力は次のとおりです。
C:\youtube-extractor>python extract_video_info.py https://www.youtube.com/watch?v=jNQXAC9IVRw
Title: Me at the zoo
Views: 172639597
Published at: 2005-04-23
Video Duration: 0:18
Video tags: me at the zoo, jawed karim, first youtube video
Likes: 8188077
Dislikes: 191986
Description: The first video on YouTube. While you wait for Part 2, listen to this great song: https://www.youtube.com/watch?v=zj82_v2R6ts
Channel Name: jawed
Channel URL: https://www.youtube.com/channel/UC4QobU6STFB0P71PMvOGN5A
Channel Subscribers: 1.98M subscribers
これです!HTMLタグからデータを抽出してから、ビデオ品質などの他のフィールドを追加する方法を知っています。
YouTubeのコメントを抽出したい場合は、これ以外にもやるべきことがたくさんあります。これには別のチュートリアルがあります。
YouTubeビデオの詳細を抽出できるだけでなく、このスキルを任意のWebサイトに適用することもできます。ウィキペディアのページを抽出したい場合は、そのためのチュートリアルがあります!それとも、Googleから気象データを取得したいですか?そのためのチュートリアルもあります。
このチュートリアルの完全なコードをここで確認してください。
リンク: https://www.thepythoncode.com/article/get-youtube-data-python