[英]AttributeError: 'NoneType' object has no attribute 'text' - Python , BeautifulSoup Error
[英]python error AttributeError: 'NoneType' object has no attribute 'text'
我是 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
在你的try..except
段中,一個直接的方法(在我看來)是使用:
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 AttributeError:
# do something...
如果我在這里遺漏了什么(從未使用過BS4 ),請告訴我。
好的,所以我發現了這個問題,當你輸入.text
你忘記了括號,所以它應該是.text()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.