質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Windows 10

Windows 10は、マイクロソフト社がリリースしたOSです。Modern UIを標準画面にした8.1から、10では再びデスクトップ主体に戻され、UIも変更されています。PCやスマホ、タブレットなど様々なデバイスに幅広く対応していることが特徴です。

URL

URL(ユニフォームリソースロケータ)とは、インターネット上のリソース(Webページや電子メールの宛先等)を特定するための形式的な記号の並びの事を言う。

YouTube

YouTubeとはユーザーがビデオをアップロード・共有・閲覧できるビデオ共有ウェブサイトです。

GitHub

GitHubは、Gitバージョン管理システムを利用したソフトウェア開発向けの共有ウェブサービスです。GitHub商用プランおよびオープンソースプロジェクト向けの無料アカウントを提供しています。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

0回答

1042閲覧

他の回答から得たYouTube Liveのアーカイブからチャットを取得するコードが自分の環境では1行目エラーになる @Python

hikatyanv

総合スコア0

Windows 10

Windows 10は、マイクロソフト社がリリースしたOSです。Modern UIを標準画面にした8.1から、10では再びデスクトップ主体に戻され、UIも変更されています。PCやスマホ、タブレットなど様々なデバイスに幅広く対応していることが特徴です。

URL

URL(ユニフォームリソースロケータ)とは、インターネット上のリソース(Webページや電子メールの宛先等)を特定するための形式的な記号の並びの事を言う。

YouTube

YouTubeとはユーザーがビデオをアップロード・共有・閲覧できるビデオ共有ウェブサイトです。

GitHub

GitHubは、Gitバージョン管理システムを利用したソフトウェア開発向けの共有ウェブサービスです。GitHub商用プランおよびオープンソースプロジェクト向けの無料アカウントを提供しています。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2021/09/24 07:21

編集2021/09/24 12:09

前提・実現したいこと

PythonでYoutube Liveのアーカイブからチャットを取得したいです。
他の方の同様の質問と回答をもとにコードを修正しましたが、自分の環境では10秒ほど待った後に1行目構文エラーとなります。

コードは下記サイトの物、修正はさらに下のURLの回答をもとに行っています。
・参照コード
https://github.com/geerlingguy/youtube_chat_crawler/blob/master/YoutubeChatReplayCrawler.py

・修正内容
https://teratail.com/questions/276731

エラーメッセージとコード内容は以下のものです。
※動画のURLとタイトルはいくつか試したうちの適当なものです

発生している問題・エラーメッセージ

エラーメッセージ (base) C:\Users\user1>python youtube_chat_crawler-master/YoutubeChatReplayCrawler.py https://www.youtube.com/watch?v=XpW8Vkv01ug SyntaxError invalid syntax (<unknown>, line 1) Comment data saved to _Splatoon2_ひさしぶりにスプラトゥーンであそんでみたにぇホロライブさくらみこ.json

該当のソースコード

Python

1ソースコード 2#!/usr/bin/env python3 3 4from bs4 import BeautifulSoup 5import ast 6import requests 7import requests_html 8import re 9import sys 10 11# Verify user supplied a YouTube URL. 12if len(sys.argv) == 1: 13 print("Please provide a YouTube URL (e.g. ./YoutubeChatReplayCrawler.py YOUTUBE_VIDEO_URL)") 14 sys.exit(0) 15 16 17# Produce a valid filename (from Django text utils). 18def get_valid_filename(s): 19 s = str(s).strip().replace(' ', '_') 20 return re.sub(r'(?u)[^-\w.]', '', s) 21 22 23# Set up variables for requests. 24target_url = sys.argv[1] 25dict_str = '' 26next_url = '' 27comment_data = [] 28session = requests_html.HTMLSession() 29headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'} 30 31# Get the video page. 32resp = session.get(target_url) 33resp.html.render(sleep=3) 34# soup = BeautifulSoup(html.text, 'html.parser') 35 36# Retrieve the title and sanitize so it is a valid filename. 37title = resp.html.find('title') 38title = title[0].text.replace(' - YouTube', '') 39title = get_valid_filename(title) 40 41# Regex match for emoji. 42RE_EMOJI = re.compile('[\U00010000-\U0010ffff]', flags=re.UNICODE) 43 44# Find any live_chat_replay elements, get URL for next live chat message. 45for iframe in resp.html.find("iframe"): 46 if "live_chat_replay" in iframe.attrs["src"]: 47 next_url = "".join(["https://www.youtube.com", iframe.attrs["src"]]) 48 49if not next_url: 50 print("Couldn't find live_chat_replay iframe. Maybe try running again?") 51 sys.exit(1) 52 53# TODO - We should fail fast if next_url is empty, otherwise you get error: 54# Invalid URL '': No schema supplied. Perhaps you meant http://? 55 56# TODO - This loop is fragile. It loops endlessly when some exceptions are hit. 57while(1): 58 59 try: 60 html = session.get(next_url, headers=headers) 61 soup = BeautifulSoup(html.text, 'lxml') 62 63 # Loop through all script tags. 64 for script in soup.find_all('script'): 65 script_text = str(script) 66 if 'ytInitialData' in script_text: 67 dict_str = ''.join(script_text.split(" = ")[1:]) 68 69 # Capitalize booleans so JSON is valid Python dict. 70 dict_str = dict_str.replace("false", "False") 71 dict_str = dict_str.replace("true", "True") 72 73 # Strip extra HTML from JSON. 74 dict_str = re.sub(r'};.*\n.+</script>', '}', dict_str) 75 76 # Correct some characters. 77 dict_str = dict_str.rstrip(" \n;") 78 79 # TODO: I don't seem to have any issues with emoji in the messages. 80 # dict_str = RE_EMOJI.sub(r'', dict_str) 81 82 # Evaluate the cleaned up JSON into a python dict. 83 dics = ast.literal_eval(dict_str) 84 85 # TODO: On the last pass this returns KeyError since there are no more 86 # continuations or actions. Should probably just break in that case. 87 continue_url = dics["continuationContents"]["liveChatContinuation"]["continuations"][0]["liveChatReplayContinuationData"]["continuation"] 88 print('Found another live chat continuation:') 89 print(continue_url) 90 next_url = "https://www.youtube.com/live_chat_replay?continuation=" + continue_url 91 92 # Extract the data for each live chat comment. 93 for samp in dics["continuationContents"]["liveChatContinuation"]["actions"]: 94 comment_data.append(str(samp) + "\n") 95 96 # next_urlが入手できなくなったら終わり 97 except requests.ConnectionError: 98 print("Connection Error") 99 continue 100 except requests.HTTPError: 101 print("HTTPError") 102 break 103 except requests.Timeout: 104 print("Timeout") 105 continue 106 except requests.exceptions.RequestException as e: 107 print(e) 108 break 109 except KeyError as e: 110 error = str(e) 111 if 'liveChatReplayContinuationData' in error: 112 print('Hit last live chat segment, finishing job.') 113 else: 114 print("KeyError") 115 print(e) 116 break 117 except SyntaxError as e: 118 print("SyntaxError") 119 print(e) 120 break 121 # continue #TODO 122 except KeyboardInterrupt: 123 break 124 except Exception: 125 print("Unexpected error:" + str(sys.exc_info()[0])) 126 127# Write the comment data to a file named after the title of the video. 128with open(title + ".json", mode='w', encoding="utf-8") as f: 129 f.writelines(comment_data) 130 131print('Comment data saved to ' + title + '.json') 132

試したこと

修正なしの場合だと上記の質問同様iframeエラーとなります。
修正後は何度か途中まで動きましたがエラー修正のために動かしていると、何をしてもLine1エラーとなるようになりました。
Pathを設定したりPathを削除しアンインストールしてやり直したりしてみましたがエラー文は変わらず。
完全に上記の質問者様と同じコードにしてみても自分の環境ではエラーでした。

(追記)
この1行を削除した場合のみエラー結果が変わりました。
この1行が悪さをしているかもしれません

Evaluate the cleaned up JSON into a python dict.

dics = ast.literal_eval(dict_str)

補足情報(FW/ツールのバージョンなど)

anaconda3
python 3.8.8
beautifulsoup4 4.9.3
使用PC:
Windows 10

ここにより詳細な情報を記載してください。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問