In BeautifulSoup, functions that search for a single result, such as find and select_one, return None if no matching element is found in the HTML. This leads to AttributeError exceptions if subsequent code attempts to use these None values as if they were actual elements.
Consider the following code snippet:
html_doc = "..." soup = BeautifulSoup(html_doc, 'html.parser') print(soup.sister) print(soup.find('a', class_='brother')) print(soup.select_one('a.brother')) soup.select_one('a.brother').text
To avoid AttributeError exceptions, it is essential to handle None returns gracefully. Here are some best practices:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3