简体   繁体   中英

How to fix this “AttributeError” in python?

I've googled my error message "AttributeError: 'NoneType' object has no attribute 'text'", but I still can't find out how to fix this error. Please help!

# -*- 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)

The error I got is

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'

You could change to use select and write css selectors that will can only return existing child p tags

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM