You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用BS4无法获取网站标题的问题求助

问题

运行以下代码后,输出为空列表,需排查解决:

import requests
from bs4 import BeautifulSoup

url = "https://youtube.com/"
r = requests.get(url)
htmlContent = r.content

soup=BeautifulSoup(htmlContent, 'html.parser')

title = soup.title()
print(title)
解决思路及修正代码

错误点分析

  • 调用方式错误:soup.title()是错误用法,title是BeautifulSoup的属性而非方法,带括号会触发标签搜索逻辑(搜索title标签的子节点),自然返回空列表。正确写法是soup.title获取title标签对象,要取文本则用soup.title.string。
  • 反爬拦截:YouTube会校验请求头,直接用requests.get发起的请求会被识别为非浏览器请求,返回的HTML内容不含正常页面的title标签,也会导致获取失败。

修正后的代码

import requests
from bs4 import BeautifulSoup

url = "https://youtube.com/"
# 添加浏览器请求头,绕过基础反爬
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}
r = requests.get(url, headers=headers)

# 先验证请求是否成功
if r.status_code == 200:
    soup = BeautifulSoup(r.text, 'html.parser')
    title_tag = soup.title
    if title_tag:
        print("页面标题:", title_tag.string)
    else:
        print("未检测到页面title标签")
else:
    print(f"请求失败,状态码:{r.status_code}")

内容的提问来源于stack exchange,提问作者Gauresh P. A.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 17:57:52