How would I get all links, or clips, from a specific channel on Twitch in Python?

丶灬走出姿态 提交于 2019-12-13 08:21:14

问题


from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
import re

req = Request("https://www.twitch.tv/directory/game/League%20of%20Legends/clips")
html_page = urlopen(req)

soup = BeautifulSoup(html_page, "html.parser")

links = []
for link in soup.findAll('a'):
    links.append(link.get('href'))

print(links)

This is the code I have this far, I'm not too sure how I would modify it to get the clip links on Twitch.


回答1:


The URLs are created dynamically, so just trying to load the HTML will not be enough. By looking at the request a browser makes to get the data, it is returned inside a JSON object.

You would either need to use something like selenium to automate a browser to get all the URLs or alternatively, requests the JSON yourself as follows:

import requests

url = "https://gql.twitch.tv/gql"
json_req = """[{"query":"query ClipsCards__Game($gameName: String!, $limit: Int, $cursor: Cursor, $criteria: GameClipsInput) { game(name: $gameName) { id clips(first: $limit, after: $cursor, criteria: $criteria) { pageInfo { hasNextPage __typename } edges { cursor node { id slug url embedURL title viewCount language curator { id login displayName __typename } game { id name boxArtURL(width: 52, height: 72) __typename } broadcaster { id login displayName __typename } thumbnailURL createdAt durationSeconds __typename } __typename } __typename } __typename } } ","variables":{"gameName":"League of Legends","limit":100,"criteria":{"languages":[],"filter":"LAST_DAY"},"cursor":"MjA="},"operationName":"ClipsCards__Game"}]"""
r = requests.post(url, data=json_req, headers={"client-id":"kimne78kx3ncx6brgo4mv6wki5h1ko"})
r_json = r.json()

edges = r_json[0]['data']['game']['clips']['edges']
urls = [edge['node']['url'] for edge in edges]

for url in urls:
    print url

This would give you the first 100 URLs starting as:

https://clips.twitch.tv/CourageousOnerousChoughWOOP
https://clips.twitch.tv/PhilanthropicAssiduousSwordHassaanChop
https://clips.twitch.tv/MistyThoughtfulLardPRChase
https://clips.twitch.tv/HotGoldenAmazonSSSsss
https://clips.twitch.tv/RelievedViscousPangolinOSsloth


来源:https://stackoverflow.com/questions/48475925/how-would-i-get-all-links-or-clips-from-a-specific-channel-on-twitch-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!