Exception 如何通过try-catch处理此异常?AttributeError:“非类型”对象没有属性“获取文本”
我想获取如图所示的趋势,但我无法获取没有tweet计数的tweet。下面的图片是我获取的没有tweet计数的tweet的错误。请让我知道如何处理此异常并打印所有推文Exception 如何通过try-catch处理此异常?AttributeError:“非类型”对象没有属性“获取文本”,exception,beautifulsoup,try-catch,tweets,Exception,Beautifulsoup,Try Catch,Tweets,我想获取如图所示的趋势,但我无法获取没有tweet计数的tweet。下面的图片是我获取的没有tweet计数的tweet的错误。请让我知道如何处理此异常并打印所有推文 from bs4 import BeautifulSoup import requests URL = "https://trends24.in/india/" html_text=requests.get(URL) soup= BeautifulSoup(html_tex
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())
您可以选择共享父级,然后在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)
所需输出应为键值对!通过这种方法,它变得不那么复杂了。建议您是否知道如何将输出转换为dict/key-value示例={'Happy easter':'123K'}、{'Good friday'、'No tweets'}之类that@PrashantPatil根据你的要求,你已经收到了答复。但是,从一个新问题的答案出发并不是社区是如何建立起来的!请检查并告知我们,我们仅限于根据最初提出的有效问题提供答案。非常感谢。应用学!这是我关于这个社区的第一个问题。下次我会记住的。