Python BeautifulSoup Error: 'AttributeError: 'NoneType' object has no attribute 'string'' - How to Fix
This error occurs when Python code attempts to access the 'string' attribute of an object that's actually 'None'. This typically happens in web scraping with BeautifulSoup when the find method fails to locate an element with the specified attributes. In this case, the soup.find('span', {'class': 'rating_num'}) call returned 'None' because no element matching those criteria was found.
To fix this, you need to check if the result of the find method is not 'None' before accessing its attributes. This can be achieved using an 'if' statement:
total_comment = soup.find('span', {'class': 'rating_num'})
if total_comment is not None:
total_comment = total_comment.string
else:
total_comment = 'N/A'
This code first assigns the result of the find method to total_comment. Then, it checks if total_comment is not 'None'. If it's not, it extracts the 'string' attribute and assigns it to total_comment. However, if total_comment is 'None', it assigns 'N/A' instead, handling the situation gracefully.
原文地址: https://www.cveoy.top/t/topic/oA4e 著作权归作者所有。请勿转载和采集!