Skip to content

Commit 8dc8967

Browse files
committed
add get_video func, closes #15
1 parent 1702498 commit 8dc8967

File tree

1 file changed

+36
-5
lines changed

1 file changed

+36
-5
lines changed

scrapetube/scrapetube.py

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -159,14 +159,37 @@ def get_search(
159159
yield video
160160

161161

162+
163+
def get_video(
164+
id: str,
165+
) -> dict:
166+
167+
"""Get a single video.
168+
169+
Parameters:
170+
id (``str``):
171+
The video id from the video you want to get.
172+
"""
173+
174+
session = get_session()
175+
url = f"https://www.youtube.com/watch?v={id}"
176+
html = get_initial_data(session, url)
177+
client = json.loads(
178+
get_json_from_html(html, "INNERTUBE_CONTEXT", 2, '"}},') + '"}}'
179+
)["client"]
180+
session.headers["X-YouTube-Client-Name"] = "1"
181+
session.headers["X-YouTube-Client-Version"] = client["clientVersion"]
182+
data = json.loads(
183+
get_json_from_html(html, "var ytInitialData = ", 0, "};") + "}"
184+
)
185+
return next(search_dict(data, "videoPrimaryInfoRenderer"))
186+
187+
188+
162189
def get_videos(
163190
url: str, api_endpoint: str, selector: str, limit: int, sleep: int, sort_by: str = None
164191
) -> Generator[dict, None, None]:
165-
session = requests.Session()
166-
session.headers[
167-
"User-Agent"
168-
] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
169-
session.headers["Accept-Language"] = "en"
192+
session = get_session()
170193
is_first = True
171194
quit_it = False
172195
count = 0
@@ -208,6 +231,14 @@ def get_videos(
208231
session.close()
209232

210233

234+
def get_session() -> requests.Session:
235+
session = requests.Session()
236+
session.headers[
237+
"User-Agent"
238+
] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
239+
session.headers["Accept-Language"] = "en"
240+
return session
241+
211242
def get_initial_data(session: requests.Session, url: str) -> str:
212243
session.cookies.set("CONSENT", "YES+cb", domain=".youtube.com")
213244
response = session.get(url)

0 commit comments

Comments
 (0)