How to handle this exception by try catch ? AttributeError: 'NoneType' object has no attribute 'get_text'

How to handle this exception by try catch ? AttributeError: 'NoneType' object has no attribute 'get_text'

enter image description here 我想获取图像中显示的趋势,但我无法获取没有推文计数的推文。(参考图片)下面是我为那些没有推文计数的推文得到的错误。请让我知道如何处理此异常并打印所有推文。

    from bs4 import BeautifulSoup
    import requests
    URL = "https://trends24.in/india/"
    html_text=requests.get(URL)
    soup= BeautifulSoup(html_text.content,'html.parser')
    results = soup.find(id='trend-list')
    job_elems = results.find_all('li')
    for job_elem in job_elems:
            print(job_elem.find('a').get_text(), job_elem.find('span').get_text())

您可以 select 对于共享父级,然后在 try except

中用 tweet-count 包装尝试抓取
from bs4 import BeautifulSoup
import requests
URL = "https://trends24.in/india/"
html_text=requests.get(URL)
soup= BeautifulSoup(html_text.content,'lxml')

for i in soup.select('#trend-list li'):
    print(i.a.text)
    try:
        print(i.select_one('.tweet-count').text)
    except:
        print("no tweets")

听写列表:

from bs4 import BeautifulSoup
import requests
URL = "https://trends24.in/india/"
html_text=requests.get(URL)
soup= BeautifulSoup(html_text.content,'lxml')

results = []

for i in soup.select('#trend-list li'):
    d = dict()
    d[i.a.text] = '' 
    try:
        val = i.select_one('.tweet-count').text
    except:
        val = "no tweets"
    finally:
        d[i.a.text] = val
        results.append(d)