使用请求和美化组获取Youtube视频标题有时出错有时有效(Python)

使用请求和美化组获取Youtube视频标题有时出错有时有效(Python),python,beautifulsoup,youtube,python-requests,screen-scraping,Python,Beautifulsoup,Youtube,Python Requests,Screen Scraping,我正在使用requests和BeautifulSoup尝试获取我提供的Youtube URL的标题。然而,它只是有时起作用。有时它返回一个错误,有时它工作;这很不一致 import requests from bs4 import BeautifulSoup def video_title(url): req = requests.get(url).text soup = BeautifulSoup(req, "html.parser") title

我正在使用requests和BeautifulSoup尝试获取我提供的Youtube URL的标题。然而,它只是有时起作用。有时它返回一个错误,有时它工作;这很不一致

import requests
from bs4 import BeautifulSoup

def video_title(url):
    req = requests.get(url).text
    soup = BeautifulSoup(req, "html.parser")
    title = soup.find("span", class_="watch-title").text
    title = title.strip()
    return title

print(video_title(input("Enter video url: ")))
此代码有时会返回给定视频的标题,其他代码则会返回此消息

Traceback (most recent call last):
  File "C:/Users/sieea/OneDrive/Code & Electronics/Python/temp.py", line 11, in <module>
    print(video_title("https://www.youtube.com/watch?v=IrV90gXmOpA"))
  File "C:/Users/sieea/OneDrive/Code & Electronics/Python/temp.py", line 7, in video_title
    title = soup.find("span", class_="watch-title").text
AttributeError: 'NoneType' object has no attribute 'text'
回溯(最近一次呼叫最后一次):
文件“C:/Users/sieea/OneDrive/Code&Electronics/Python/temp.py”,第11行,在
打印(视频标题)https://www.youtube.com/watch?v=IrV90gXmOpA"))
文件“C:/Users/sieea/OneDrive/Code&Electronics/Python/temp.py”,第7行,视频标题
title=soup.find(“span”,class=“watch title”).text
AttributeError:“非类型”对象没有属性“文本”

为什么它只是偶尔出错?我如何才能使它始终工作?

尝试指定不同的
用户代理
-在这种情况下,我使用Google Bot中的用户代理字符串。在我的测试中,使用此标头,我无法再现异常:

import requests
from bs4 import BeautifulSoup

url = 'https://www.youtube.com/watch?v=xbs7FT7dXYc'

headers = {'User-Agent': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'}

req = requests.get(url, headers=headers).text
soup = BeautifulSoup(req, "html.parser")

title = soup.find("span", class_="watch-title").text
title = title.strip()
print(title)
印刷品:

Videos for Cats to Watch - 8 Hour Bird Bonanza