采用模拟浏览器爬虫去哪儿网https://piao.qunar.com景点信息数据并保存为csv文件的代码
时间: 2024-01-17 13:03:51 浏览: 37
以下是一个简单的Python爬虫示例,可用于爬取去哪儿网的景点信息并将其保存为CSV文件:
```python
import requests
from bs4 import BeautifulSoup
import csv
# 设置请求头
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'}
# 设置URL
url = 'https://piao.qunar.com/'
# 发送请求
response = requests.get(url, headers=headers)
# 解析HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 获取所有景点信息
scenic_spots = soup.find_all('div', {'class': 'mp-description'})
# 将景点信息保存到CSV文件
with open('scenic_spots.csv', 'w', newline='', encoding='utf-8-sig') as file:
writer = csv.writer(file)
writer.writerow(['景点名称', '景点链接', '景点描述'])
for spot in scenic_spots:
name = spot.find('a').get_text()
link = 'https://piao.qunar.com' + spot.find('a')['href']
description = spot.find('p').get_text()
writer.writerow([name, link, description])
```
需要注意的几个点:
- 由于去哪儿网的反爬虫机制比较严格,所以需要设置请求头模拟浏览器的请求。
- 使用BeautifulSoup解析HTML页面,定位到包含景点信息的标签,提取出景点名称、链接和描述信息。
- 使用CSV模块将景点信息写入CSV文件,注意设置编码格式和换行符。