python爬取马蜂窝旅游攻略
时间: 2023-10-03 20:09:01 浏览: 54
可以使用Python中的requests和BeautifulSoup库来爬取马蜂窝旅游攻略。
首先,使用requests库向马蜂窝网站发送请求,获取需要爬取的页面内容,例如:
```python
import requests
url = 'https://www.mafengwo.cn/gonglve/'
response = requests.get(url)
html = response.text
```
接着,使用BeautifulSoup库来解析页面内容,提取需要的信息。例如,如果我们需要爬取攻略标题、作者、时间和浏览量,可以使用以下代码:
```python
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
articles = soup.find_all('div', class_='post-item')
for article in articles:
title = article.find('a', class_='title').text.strip()
author = article.find('a', class_='nickname').text.strip()
time = article.find('span', class_='time').text.strip()
views = article.find('span', class_='views').text.strip()
print(title, author, time, views)
```
以上代码中,我们使用`find_all`方法查找所有攻略文章的`div`元素,并遍历每篇文章,然后使用`find`方法找到文章标题、作者、时间和浏览量所在的元素,并使用`text`属性获取其文本内容。
当然,还有其他方式可以根据自己的需求来提取想要的信息。需要注意的是,爬取网站信息时需要遵守相关法律法规和网站的规定,不得进行非法操作。