Skip to main content
 首页 » 编程设计

python 错误AttributeError : 'NoneType' object has no attribute 'text'

2025年05月04日12虾米哥

我是 python 新手,我的代码如下:

import warnings 
import requests 
from colorama import init 
init(autoreset=True) 
 
from requests.packages.urllib3.exceptions import InsecureRequestWarning 
warnings.simplefilter("ignore", UserWarning) 
warnings.simplefilter('ignore', InsecureRequestWarning) 
 
from bs4 import BeautifulSoup as BS 
 
 
with open('ips.txt','r') as urls: 
    for url in urls.readlines(): 
        req = url.strip() 
        try: 
            page=requests.get(req, verify=False, allow_redirects=False, stream=True, timeout=10) 
            soup = BS(page.text) 
 
            print('\033[32m' + req + ' - Title: ', soup.find('title').text) 
        except requests.RequestException as e: 
            print('[!] Timeout!') 

我正在尝试打印来自 IPs.txt 的链接标题

输出: https://gyazo.com/fadb8f3427ecdeebb252779bd253a15c

我有错误:

Traceback (most recent call last): 
  File "scratch_1.py", line 19, in <module> 
    print('\033[32m' + req + ' - Title: ', soup.find('title').text) 
AttributeError: 'NoneType' object has no attribute 'text' 

有什么办法解决这个问题吗?

谢谢 问候。

请您参考如下方法:

如果汤没有<title>然后标记 soup.find('title')返回 None .在尝试使用它之前必须检查返回值:

title_tag = soup.find('title') 
if title_tag: 
    # Do something with title_tag.title 
    # For example, extract the title as string title_tag.title.string 
else:  
    # No title, do something else