```python
import requests
from bs4 import BeautifulSoup
目标网址
url = 'https://www.example.com'
发送请求
response = requests.get(url)
检查请求状态
if response.status_code == 200:
解析网页内容
soup = BeautifulSoup(response.text, 'html.parser')
提取所需信息,例如提取所有的标题
titles = soup.find_all('h1')
输出结果
for title in titles:
print(title.text)
else:
print('请求失败,状态码:', response.status_code)
这个示例中,我们首先导入了`requests`和`BeautifulSoup`库,然后向指定的URL发送HTTP GET请求。如果请求成功(状态码为200),我们使用`BeautifulSoup`解析返回的HTML内容,并提取所有`
`标签的文本内容,最后将它们打印出来。如果请求失败,则打印出失败的状态码。
请确保在运行此代码之前已经安装了`requests`和`BeautifulSoup`库。如果尚未安装,可以通过以下命令安装:
```bash
pip install requests
pip install beautifulsoup4
如果你需要提取其他类型的信息,比如链接、图片或其他HTML元素,你可以根据`BeautifulSoup`的文档来修改代码。