Ошибка нетипа не исправлена ​​очисткой текста условия if-else BeautifulSoup - PullRequest
1 голос
/ 18 апреля 2020

В настоящее время я пытаюсь извлечь текст статей из нескольких RSS-каналов с одного сайта. Я написал код, который собирает URL для этих нескольких RSS-каналов со страницы RSS, а затем собирает URL для статей из отдельных RSS-каналов. Затем код пытается извлечь текст из каждого уникального URL статьи. Но здесь я сталкиваюсь с трудностями.

Моя функция извлечения текста возвращает ошибку «NoneType» объект не имеет атрибута «text». Однако я поместил условие if / else, чтобы попытаться справиться с NoneTypes.

Почему возникает ошибка атрибута, даже если существует условие if для его обхода?

Здесь минимальный воспроизводимый пример использования Newspaper3k для получения URL-адресов в отличие от RSS-каналов. Пожалуйста, дайте мне знать, как я могу уточнить или исправить мой вопрос.

#Libraries to be used
from bs4 import BeautifulSoup
import requests
import newspaper as np

#function to extract text from url
def extract_text(url_list):  
    art_list = []
    for url in url_list:
        page = requests.get(url)
        if page is not None: #This is not working
            urlsoup = BeautifulSoup(page.text, 'html.parser')
            if urlsoup is not None: #This did not fix
                text = urlsoup.find('div', id='article-content').text
                art_list.append(text)
        else:
            art_list.append('')
    return art_list

#get set of articles
voa_chinese = np.build('https://www.voachinese.com/', 
                       language='zh', memoize_articles=False)

#get set of urls
url_list = []

for article in voa_chinese.articles:
    url_list.append(article.url)

#Run function on url list
article_list = extract_text(url_list)

Вот сообщение об ошибке:

AttributeError                            Traceback (most recent call last)
<ipython-input-26-251a9e599cc9> in <module>()
      8     url_list.append(article.url)
      9 
---> 10 article_list = extract_text(url_list)

<ipython-input-25-0fa49893d593> in extract_text(url_list)
     14             urlsoup = BeautifulSoup(page.text, 'html.parser')
     15             if urlsoup is not None:
---> 16                 text = urlsoup.find('div', id='article-content').text
     17                 art_list.append(text)
     18         else:

AttributeError: 'NoneType' object has no attribute 'text'

Ответы [ 2 ]

0 голосов
/ 21 апреля 2020

Попробуйте изменить это:

if urlsoup is not None: #This did not fix
    text = urlsoup.find('div', id='article-content').text
    art_list.append(text)

на что-то вроде

if urlsoup is not None: 
    item = urlsoup.find('div', id='article-content')
    if item.text is not None:
       art_list.append(item.text)
0 голосов
/ 21 апреля 2020

В качестве альтернативы используйте try catch:

try:
   text = urlsoup.find('div', id='article-content').text
except:
   text = "Not Found "    #or do something as desired 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...