永远保持一颗求知的心,不要被已知所束缚。
第二篇就不想写了,这样不行的。
A任务:爬取stackoverflow的问题和详细内容数据并保存csv文件
用Firefox分析网页元素:

可以看到我们要爬取的所有链接可以由这个目录进,查询到目的网页的链接地址:

进入目的子网页并分析元素:

网页分析完成以后编写一简单爬虫进行试验:
import scrapy
class StackOverflowSpider(scrapy.Spider):
name = "Stackoverflow"
start_urls=["https://stackoverflow.com/questions?sort=votes"]
def parse(self,response):
for href in response.css('.question-summary h3 a::attr(href)'):
full_url = response.urljoin(href.extract())
yield scrapy.Request(full_url,callback=self.parse_question)
def parse_question(self,response):
yield {
'title':response.css('.inner-content h1 a::text').extract()[0],
'votes':response.css(".vote .vote-count-post::text").extract()[0],
'body':response.css(".post-text").extract()[0],
'tags':response.css('.post-taglist .post-tag::text').extract(),
'link':response.url,
}
执行爬虫并保存为csv文件:
> scrapy runspider scrapy1.py -o abc.csv
就可以在文件夹下发现已经存有数据的abc.csv,需要重点学习css选择器的使用规则。
网友评论