如何将 YouTube 频道创作者和 link 抓取到他们的频道?

How to I scrape The YouTube Channel Creator and link to their channel?

我正在尝试使用 beautifulsoup 从视频页面中提取频道创建者的姓名以及他们频道的 link。

我试过使用 class_ 关键字参数。结果我得到 [] 。我应该怎么办? 我是否需要像他们在 Beautifulsoup 中所说的那样通过父 div 标记然后 "go down"? should/could 我如何为那个特定的标签 soup.find 和 class?

soup = BeautifulSoup(response.text, "html.parser")

videotitle = soup.find("meta", {"property":"og:title"})["content"]

videochannel = soup.body.find_all("a", class_="yt-simple-endpoint style-scope yt-formatted-string")

您可以使用 Selenium 打开浏览器,然后给它一个 URL 并使用 CSS 选择器定位元素。下面是一些可以定位您要查找的元素的起始代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

# Opens a chrome browser window
browser = webdriver.Chrome(executable_path="/PATH/TO/CHROMEDRIVER")                            

# Navigates to a link
browser.get("https://www.youtube.com/watch?v=hHW1oY26kxQ")

time.sleep(5)

# Locate the element using a CSS selector
chilledCowElem = browser.find_element_by_css_selector("div.ytd-channel-name a")

# Access the name of the channel and gets its href value
print(chilledCowElem.text)
print(chilledCowElem.get_attribute("href"))

time.sleep(5)
browser.quit()

输出:

您必须在第 5 行插入驱动程序的路径。我使用的是 Chrome 的驱动程序,您可以在此处下载 https://sites.google.com/a/chromium.org/chromedriver/downloads. Here's the selenium docs if you want to find out more on how to set it up for your project and use it: https://selenium-python.readthedocs.io/installation.html#drivers

好的,首先,您不需要 Selenium。您很少需要 Selenium。即使有 javascript/ajax 个电话。如果您深入 ajax 调用,您只需要来回输入 GET/POST XSFR-Token 密钥,直到获得所需的数据。与通过请求进行的简单 HTTP 调用相比,Selenium 确实很重、臃肿且缓慢。尽可能避免它。如果您完全被困住了并且不知道如何导航 ajax-post/request 个令牌,那么请务必使用它。有总比没有好。

现在,您没有得到所需响应的原因是您的浏览器和 python-requests 包看到的是两个完全不同的响应。所以从一开始,你甚至无法导航你要去的地方,因为你看错了地图。浏览器有自己的自定义地图,而 requests 包有一个完全不同的地图。这就是 PPRINT 包派上用场的地方(如下图)。 PPRINT 以更清晰的结构格式化文本,帮助您更清楚地查看返回的响应。

最后,我使用 Anaconda 的 Jupyter Notebook,因为它允许我一次处理代码块,而不必 运行 整个程序。如果您还没有使用 Jupyter Notebooks,我建议您试一试。它将帮助您了解一切如何与部分输出一起工作 "frozen in time"。

祝你好运!希望你不要太气馁。这一切都需要时间。

这是我用来解决您的问题的工作流程:

from bs4 import BeautifulSoup
import requests
import pprint as pp

url = "https://www.youtube.com/watch?v=hHW1oY26kxQ"

response = requests.get(url, headers={'User-Agent':USER_AGENT})
soup = BeautifulSoup(response.text, 'lxml')

for div in soup.find_all("div", {"id": "watch7-user-header"}):
    for a in div.find_all("a"):
        continue
    print(a["href"])