爬取马蜂窝网站北京景点信息的具体代码
时间: 2023-08-14 10:07:49 浏览: 62
以下是使用 Python 爬虫工具 Scrapy 爬取马蜂窝网站北京景点信息的代码示例:
```python
import scrapy
class BeijingScenicSpider(scrapy.Spider):
name = 'beijing_scenic'
allowed_domains = ['www.mafengwo.cn']
start_urls = ['https://www.mafengwo.cn/search/s.php?q=北京景点']
def parse(self, response):
for scenic in response.css('ul.list li'):
yield {
'name': scenic.css('h3.tit a::text').get(),
'address': scenic.css('p.row:nth-child(2) a::text').get(),
'score': scenic.css('p.row:nth-child(3) span.s::text').get(),
'comments': scenic.css('p.row:nth-child(3) a::text').get(),
}
next_page = response.css('a.next::attr(href)').get()
if next_page is not None:
yield response.follow(next_page, self.parse)
```
代码解释:
1. 在 `start_urls` 中指定起始 URL,即马蜂窝网站搜索北京景点的网址。
2. 在 `parse` 函数中,使用 CSS 选择器获取景点的名称、地址、评分、评论等信息,并通过 `yield` 返回结果。
3. 使用 `response.follow` 方法处理下一页的 URL,继续爬取后续页面的数据。
需要注意的是,爬取数据时需要尊重网站的规则,不要过度请求网站,避免对网站造成过大的负担。同时,还需要注意数据的质量和准确性,避免因为数据的问题导致后续分析结果不准确。