用 python 写爬虫
时间: 2023-08-20 12:06:43 浏览: 31
以下是使用Python实现爬取网页的基本步骤:
1. 导入必要的库
```
import requests
from bs4 import BeautifulSoup
```
2. 发送请求并获取网页内容
```
url = 'https://www.example.com'
response = requests.get(url)
content = response.content
```
3. 解析网页内容
```
soup = BeautifulSoup(content, 'html.parser')
```
4. 提取需要的信息
```
# 查找所有的超链接并打印链接文本和URL
for link in soup.find_all('a'):
print(link.text, link.get('href'))
```
5. 将结果保存到本地文件中
```
with open('output.txt', 'w') as f:
f.write('网页标题:' + soup.title.string + '\n')
for link in soup.find_all('a'):
f.write(link.text + ' ' + link.get('href') + '\n')
```
完整的代码示例:
```
import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com'
response = requests.get(url)
content = response.content
soup = BeautifulSoup(content, 'html.parser')
with open('output.txt', 'w') as f:
f.write('网页标题:' + soup.title.string + '\n')
for link in soup.find_all('a'):
f.write(link.text + ' ' + link.get('href') + '\n')
```
这段代码通过`requests`库发送HTTP请求获取网页内容,并使用`BeautifulSoup`库解析网页内容。然后遍历所有的超链接,将链接文本和URL保存到本地文件中。请注意,这只是一个简单的爬虫示例,实际的爬虫需要针对不同的网站进行适当的调整和优化。