[英]BeautifulSoup find_all() AttributeError: 'NoneType' object has no attribute 'a'
When I just do the soup.find() method I get the result that I want, it is when I try to loop and use find_all() when it goes wrong.当我只是执行 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()
It prints a couple of results and then it throws an error as shown below:它打印了几个结果,然后抛出一个错误,如下所示:
Χρηματιστήριο: Τι δεν έχει τιμολογήσει ακόμα η αγορά – Δεν φτάνει η αντίδραση της 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'
I just want to print all of the article titles with the link underneath.我只想用下面的链接打印所有文章标题。 Any suggestions would be appreciated任何建议,将不胜感激
for article in find:
try:
headline = article.h3.a.text
print(headline)
link =article.h3.a['href']
print(link)
print()
except AttributeError:
pass
You can use try
and except
Blocks.您可以使用try
和except
块。 It has printed 24
articles已打印24
篇文章
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.