如何判断requests和BeautifulSoup安装成功
时间: 2024-11-03 20:08:13 浏览: 20
判断`requests`和`BeautifulSoup4`这两个Python库是否安装成功的常见方法是在Python交互环境中运行一些测试代码。以下是步骤:
1. **requests**:
- 打开命令行或终端,然后输入并运行以下命令:
```python
import requests
try:
response = requests.get('https://www.baidu.com')
print(response.status_code) # 如果返回200,说明requests安装成功
except ImportError:
print("requests library not found.")
```
如果没有错误,并且能够获取到百度首页的状态码,那么`requests`就已成功安装。
2. **BeautifulSoup4**:
- 再次导入并尝试解析一个网页,例如:
```python
from bs4 import BeautifulSoup
try:
html_content = requests.get('https://www.example.com').text
soup = BeautifulSoup(html_content, 'html.parser')
print(soup.prettify()) # 如果能正常打印HTML内容,说明BeautifulSoup也安装成功
except ImportError:
print("BeautifulSoup4 library not found.")
except Exception as e:
print(f"Error occurred while parsing HTML: {e}")
```
如果没有异常并且能看到HTML结构,说明`BeautifulSoup4`已经安装好。
如果上述代码运行顺利,说明两个库都安装成功了。
阅读全文