【问题标题】:python error AttributeError: 'NoneType' object has no attribute 'text'python错误AttributeError:'NoneType'对象没有属性'text'
【发布时间】:2019-07-18 09:26:02
【问题描述】:

我是 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'

有什么办法解决吗?

谢谢 问候。

【问题讨论】:

    标签: python python-3.x beautifulsoup


    【解决方案1】:

    在您的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)。

    【讨论】:

      【解决方案2】:

      如果汤没有&lt;title&gt; 标签,则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
      

      【讨论】:

      • 它打印 XXX 如何摆脱它并让它只打印“XXX”。没有废话>
      • 这是一个不同的问题,但我添加了一个示例。
      【解决方案3】:

      好的,所以我发现了问题,当您输入 .text 时,您忘记了括号,所以它应该是 .text()

      【讨论】:

      • 它不可调用,会报错:Traceback (most recent call last): File "scratch_1.py", line 20, in &lt;module&gt; print('\033[32m' + req + ' - Title: ', soup.find('title').text()) TypeError: 'str' object is not callable
      猜你喜欢
      • 2019-01-10
      • 2023-03-03
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多