下面我们使用 scrapy 写一个爬虫脚本爬取蓝桥课程页面课程名称、学习人数信息并保存为 JSON 文本。课程页面的地址是 httpswwwlanqiaocncourses。import scrapyclass ShiyanlouCoursesSpiderscrapySpider 使用 scrapy 爬取页面数据需要编写一个爬虫类该爬虫类要继承 scrapySpider 类 在
在parse方法中,我们可以使用Scrapy提供的Selector来提取页面数据,并将提取的数据保存为JSON文本并打印出来。以下是完整的代码:
import scrapy
import json
class ShiyanlouCoursesSpider(scrapy.Spider):
name = 'shiyanlou-courses'
start_urls = ['https://www.lanqiao.cn/courses/']
def parse(self, response):
selector = scrapy.Selector(response)
courses = selector.xpath('//div[@class="course-card-container"]')
for course in courses:
name = course.xpath('.//h4/text()').extract_first().strip()
students = course.xpath('.//span[@class="learn-number"]/text()').extract_first()
yield {
'name': name,
'students': students
}
def closed(self, reason):
courses = list(self.parse(scrapy.Response(url=self.start_urls[0])))
with open('courses.json', 'w') as f:
json.dump(courses, f, indent=4)
print('Courses saved as courses.json')
在这个代码中,我们在parse方法中使用XPath选择器提取课程名称和学习人数信息,并通过yield关键字将提取的数据返回。在closed方法中,我们将parse方法的返回结果转换为列表,并使用json.dump方法将列表保存为JSON文本。最后打印出保存成功的提示信息。
原文地址: https://www.cveoy.top/t/topic/jeO5 著作权归作者所有。请勿转载和采集!