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)

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

# 查找需要的信息
info = soup.find('div', {'class': 'info'})

# 提取信息
title = info.find('h1').text.strip()
author = info.find('span', {'class': 'author'}).text.strip()
content = info.find('div', {'class': 'content'}).text.strip()

# 存储数据
with open('data.txt', 'w', encoding='utf-8') as f:
    f.write(title + '\n')
    f.write(author + '\n')
    f.write(content + '\n')
```

这个模板包括以下几个步骤:

1. 设置请求头,模拟浏览器访问。
2. 发送请求,获取网页内容。
3. 解析网页,使用BeautifulSoup库。
4. 查找需要的信息,使用find()方法。
5. 提取信息,使用text属性和strip()方法。
6. 存储数据,使用open()函数和write()方法。

这个模板可以适用于大部分的网页爬取任务,只需要根据具体的需求修改一些细节即可。

猜你喜欢

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