python爬虫爬取网页数据
时间: 2023-10-06 14:13:37 浏览: 39
Python 爬虫可以使用第三方库 `requests` 和 `beautifulsoup4`,它们可以帮助我们发送 HTTP 请求并解析 HTML。
以下是一个简单的 Python 爬虫示例,用于爬取百度首页的标题:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.baidu.com/'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.title.string
print(title)
```
解释:
- `requests.get(url)` 发送 HTTP GET 请求并获取响应。
- `response.text` 获取响应文本。
- `BeautifulSoup(response.text, 'html.parser')` 将 HTML 文本解析为 BeautifulSoup 对象。
- `soup.title.string` 获取页面标题文本。
你可以根据自己的需求修改代码来爬取其他网页上的数据。需要注意的是,爬取网页数据需要遵守网站的爬虫规则,不要进行恶意行为。