使用 Beautifulsoup 抓取视频说明
Video description scraping with Beautifulsoup
我试图在 YouTube 上的视频说明中抓取 link,但列表始终 return 为空。
我尝试更改我正在抓取的标签,但输出和错误消息都没有变化。
这是我使用的代码:
from bs4 import BeautifulSoup
import requests
source = requests.get('https://www.youtube.com/watch?v=gqUqGaXipe8').text
soup = BeautifulSoup(source, 'lxml')
link = [i['href'] for i in soup.findAll('a', class_='yt-simple-endpoint style-scope yt-formatted-string', href=True)]
print(link)
出了什么问题,我该如何解决?
在您的情况下,requests
并不 return 页面的整个 HTML 结构。如果 Youtube 是使用 JavaScript 填充数据,我们必须 运行 通过真正的浏览器获取页面源,例如 Chrome Headless 使用 Selenium
库。这是一般的解决方案:
from bs4 import BeautifulSoup
from selenium import webdriver
import time
options = webdriver.ChromeOptions()
options.add_argument('--headless')
driver = webdriver.Chrome(options = options)
url = "https://www.youtube.com/watch?v=Oh1nqnZAKxw"
driver.get(url)
time.sleep(2)
soup = BeautifulSoup(driver.page_source, 'html.parser')
driver.quit()
link = [i['href'] for i in soup.select('div#meta div#description [href]')]
print(link)
我试图在 YouTube 上的视频说明中抓取 link,但列表始终 return 为空。
我尝试更改我正在抓取的标签,但输出和错误消息都没有变化。
这是我使用的代码:
from bs4 import BeautifulSoup
import requests
source = requests.get('https://www.youtube.com/watch?v=gqUqGaXipe8').text
soup = BeautifulSoup(source, 'lxml')
link = [i['href'] for i in soup.findAll('a', class_='yt-simple-endpoint style-scope yt-formatted-string', href=True)]
print(link)
出了什么问题,我该如何解决?
在您的情况下,requests
并不 return 页面的整个 HTML 结构。如果 Youtube 是使用 JavaScript 填充数据,我们必须 运行 通过真正的浏览器获取页面源,例如 Chrome Headless 使用 Selenium
库。这是一般的解决方案:
from bs4 import BeautifulSoup
from selenium import webdriver
import time
options = webdriver.ChromeOptions()
options.add_argument('--headless')
driver = webdriver.Chrome(options = options)
url = "https://www.youtube.com/watch?v=Oh1nqnZAKxw"
driver.get(url)
time.sleep(2)
soup = BeautifulSoup(driver.page_source, 'html.parser')
driver.quit()
link = [i['href'] for i in soup.select('div#meta div#description [href]')]
print(link)