使用bs4网页爬取遇TypeError:'NoneType'对象不可下标访问
问题分析与解决
错误原因
你碰到的TypeError: 'NoneType' object is not subscriptable,本质是代码里video_tag.find("a")没找到对应的<a>标签,返回了None,这时直接去访问['href']就触发了错误。
另外还有个核心问题:Plex的视频页面需要登录才能访问,你直接用requests.get()拿到的是未登录状态的页面,里面根本没有实际的<video>标签,后续的提取逻辑从一开始就不成立。
修复方案
1. 先做安全判断,避免None值报错
不管页面内容是否正常,都要先检查find()的结果是否存在,再去访问属性:
import requests from bs4 import BeautifulSoup Web_url = "https://watch.plex.tv/show/hannibal/season/1/episode/9" r = requests.get(Web_url) soup = BeautifulSoup(r.content, 'html.parser') video_tags = soup.find_all("video") print("Total", len(video_tags), "videos found") if len(video_tags) !=0: for video_tag in video_tags: a_tag = video_tag.find("a") if a_tag: # 先确认a标签存在再取href video_url = a_tag['href'] print(video_url) else: print("当前video标签下没有找到a标签")
2. 解决Plex的登录限制
Plex的视频内容需要登录才能查看,直接用requests请求会得到未登录页面。你需要用会话保持Cookie,模拟登录流程:
import requests from bs4 import BeautifulSoup # 创建会话,自动保持登录Cookie session = requests.Session() # 模拟登录(需替换成你的Plex账号密码,接口可能需根据实际调整) login_payload = { 'username': '你的Plex账号', 'password': '你的Plex密码' } session.post('https://plex.tv/users/sign_in', data=login_payload) # 用登录后的会话请求目标页面 Web_url = "https://watch.plex.tv/show/hannibal/season/1/episode/9" r = session.get(Web_url) soup = BeautifulSoup(r.content, 'html.parser') video_tags = soup.find_all("video") print("Total", len(video_tags), "videos found") if len(video_tags) !=0: for video_tag in video_tags: a_tag = video_tag.find("a") if a_tag: video_url = a_tag['href'] print(video_url) else: print("当前video标签下没有a标签")
3. 应对动态加载的情况
如果登录后还是找不到<video>标签,大概率是页面内容通过JavaScript动态渲染的,这时要用selenium模拟浏览器加载:
from selenium import webdriver from selenium.webdriver.common.by import By import time # 初始化浏览器 driver = webdriver.Chrome() driver.get("https://watch.plex.tv/show/hannibal/season/1/episode/9") # 等待页面加载(可手动登录,或添加自动登录逻辑) time.sleep(5) # 查找所有video标签 video_tags = driver.find_elements(By.TAG_NAME, "video") print("Total", len(video_tags), "videos found") for video_tag in video_tags: a_tags = video_tag.find_elements(By.TAG_NAME, "a") if a_tags: video_url = a_tags[0].get_attribute('href') print(video_url) else: print("当前video标签下没有a标签") driver.quit()
额外提醒
直接爬取Plex的视频内容可能违反其服务条款,建议优先查看Plex官方API文档,通过合法方式获取视频信息。
内容的提问来源于stack exchange,提问作者Suikurix
相关产品推荐
相关产品推荐

