【问题标题】:BeautifulSoup find_all() AttributeError: 'NoneType' object has no attribute 'a'BeautifulSoup find_all() AttributeError: 'NoneType' 对象没有属性 'a'
【发布时间】:2021-05-31 23:56:49
【问题描述】:

当我只执行soup.find() 方法时,我得到了我想要的结果,这是当我尝试循环并在出错时使用find_all() 时。

 source = requests.get('https://www.mononews.gr/').text
 soup = BeautifulSoup(source,'lxml')

 find  = soup.find_all('section',class_="story-package-module")
 for article in find:
    
    #headline
    headline = article.h3.a.text
    print(headline)

    #link
    link =article.h3.find('a',class_="story-package-module__story__headline-link")['href']
    print(link)
    
    print()

它会打印几个结果,然后抛出如下所示的错误:

Χρηματιστήριο: Τι δεν έχει τιμολογήσει ακόμα η αγορά – Δεν φτάνει η αντίδραση της Aegean    
https://www.mononews.gr/agores/chrimatistirio-ti-den-echi-tmologisi-akoma-i-agora-den-ftani-i-antidrasi-tis-aegean


Κάναμε σκι με CR-V (video)! 
https://www.mononews.gr/auto/kaname-ski-me-crv-video


Kαραμανλής: Έγινε το πρώτο βήμα για την επέκταση του Μετρό παράλληλα με την λεωφόρο Κηφισίας 
https://www.mononews.gr/oikonomia/karamanlis-egine-to-proto-vima-gia-tin-epektasi-tou-metro-parallila-me-tin-leoforo-kifisias

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-92-391906396ad6> in <module>
      7 
      8     #headline
----> 9     headline = article.h3.a.text
     10     print(headline)
     11 

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

我只想打印所有带有链接的文章标题。 任何建议将不胜感激

【问题讨论】:

    标签: python parsing web-scraping beautifulsoup


    【解决方案1】:
    for article in find:
        try:
            
            headline = article.h3.a.text
            print(headline)
            link =article.h3.a['href']
            print(link)
            print()
        except AttributeError:
            pass
                
    

    您可以使用 tryexcept 块。已打印24文章

    【讨论】:

    • 非常感谢,已经解决了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多