我将如何从 Python 中 Twitch 上的特定频道获取所有链接或剪辑


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)

这是我到目前为止的代码,我不太确定如何修改它以获取 Twitch 上的剪辑链接。

URL 是动态创建的,因此仅尝试加载 HTML 是不够的。通过查看浏览器为获取数据而发出的请求,它会在 JSON 对象中返回。

您需要使用 selenium 之类的东西来自动化浏览器以获取所有 URL,或者自己请求 JSON,如下所示:

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

这将为您提供前 100 个 URL,开头为:

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

最新更新