我已经用Google搜索我的错误消息“ AttributeError:'NoneType'对象没有属性'text'”,但是我仍然找不到解决该错误的方法。请帮忙!

# -*- coding: UTF-8 -*-
import io
import sys

sys.stdout=io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')
import requests
from bs4 import BeautifulSoup

print('蘋果今日焦點')
dom = requests.get('http://www.appledaily.com.tw/appledaily/hotdaily/headline').text
soup = BeautifulSoup(dom, 'html5lib')
for ele in soup.find('ul', 'all').find_all('li'):
    print(
        ele.find('div', 'aht_title_num').text,
        ele.find('div', 'aht_title').text,
       # ele.find('div', 'aht_pv_num').text
    )
print('---------------------------------')
print('自由今日焦點')
dom = requests.get('http://news.ltn.com.tw/list/breakingnews').text
soup = BeautifulSoup(dom, 'html5lib')
for ele in soup.find('ul','list').find_all('li'):
    print(ele.find('p').text)


我得到的错误是

Traceback (most recent call last):
File "ch3-news.py",
line 23, in <module> print(ele.find('p').text)
AttributeError: 'NoneType' object has no attribute 'text'

最佳答案

您可以更改为使用select并编写仅可以返回现有子p标记的css选择器

import requests
from bs4 import BeautifulSoup

dom = requests.get('http://news.ltn.com.tw/list/breakingnews').text
soup = BeautifulSoup(dom, 'html5lib')
for ele in soup.select('ul li p ,  list li p'):
    print(ele.text)

关于python - 如何在python中修复此“AttributeError”?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57107074/

10-12 19:26