from bs4 import BeautifulSoup
from urllib.request import urlopen, quote
import requests
def load_movie_list(word):
url = "https://www.youtube.com/results?search_query={}".format(quote(word))
html = urlopen(url)
bsOjb = BeautifulSoup(html, features="html.parser")
li_bsObjs = bsOjb.findAll("li")
relation_videos = []
for li_tag in li_bsObjs:
img_tag = li_tag.find("img")
if img_tag is None:
continue
try:
img = img_tag["data-thumb"]
except KeyError:
continue
href = li_tag.find("a")["href"]
if "UC" in href:
continue
try:
print(li_tag)
title = li_tag.findAll("a")[1].text
except IndexError:
continue
relation_videos.append({
"title" : title,
"href" : href.replace("/watch?v=","").replace("/channel/", ""),
"img" : img
})
return relation_videos
youtubeへアクセスする
コードは以下の部分
url = "https://www.youtube.com/watch?v=" + video_id
html = urlopen(url)
bsOjb = BeautifulSoup(html, features="html.parser")
youtubeのurlへアクセスしhtmlを手に入れた後、BeautifulSoupというパーサーライブラリーへhtmlを渡すli要素を全て取得する
コード
li_bsObjs = bsOjb.findAll("li")
htmlを勉強したことのある人ならわかりますが,「li」というタグは、リストを書くために使用します
youtubeも動画のリストをhtmlで表現するためにliを使っています
したがって、動画のリストを手に入れたい時は、li要素を全て取得すればいいです
li内のimgを取得する
img_tag = li_tag.find("img")
if img_tag is None:
continue
try:
img = img_tag["data-thumb"]
except KeyError:
continue
img要素のdata-thumb属性値を手に入れますちなみにこのdata-thumbのthumbはthumbnailのthumb
thumbnailはサムネイルのことですね
つまりdata-thumbはサムネイルデータのこと
同時に、li内にあるaタグ内からタイトルとurlを手に入れる
href = li_tag.find("a")["href"]
if "UC" in href:
continue
try:
print(li_tag)
title = li_tag.findAll("a")[1].text
except IndexError:
continue
手に入れた情報をまとめる
relation_videos.append({
"title" : title,
"href" : href.replace("/watch?v=","").replace("/channel/", ""),
"img" : img
})
ここで、今まで手に入れたタイトル、url、画像のデータをまとめます。