python爬虫万能模板

以下是一个简单的 Python 爬虫模板,可以用于爬取网页数据:

```python
import requests
from bs4 import BeautifulSoup

# 设置请求头,模拟浏览器访问
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}

# 发送请求
response = requests.get(url, headers=headers)

# 解析 HTML
soup = BeautifulSoup(response.text, 'html.parser')

# 获取需要的数据
data = soup.find('div', {'class': 'example'})

# 输出结果
print(data.text)
```

其中,`requests` 库用于发送 HTTP 请求,`BeautifulSoup` 库用于解析 HTML,`headers` 变量用于设置请求头,模拟浏览器访问。在实际使用中,需要根据具体的网站和数据结构进行相应的修改。

猜你喜欢

转载自blog.csdn.net/weixin_73725158/article/details/131417022