读者最好对 Python 和爬虫有一些了解,所以关于 Scrapy 一些信息比如如何安装的方法等我就不介绍了。
案例
爬下知乎某个话题下面的精华问答,包括推荐回答,回答者,问题简介,问题链接。爬完数据存在本地文件。
新建工程
首先新建一个 Scrapy 工程,在工程目录命令行执行
scrapy startproject zhihu
之后生成的文件有几个是需要我们知道的
items.py 是定义我们的数据结构的
pipelines.py 是处理数据的,一般就在里面存数据库,或者文件
settings.py 是配置爬虫信息,比如 USER_AGENT 还有 ITEM_PIPELINES 这些
./spiders 文件夹下面需要我们建立我们的爬虫程序
编码
在 ./spiders 新建一个 zhihu_questions_spider.py 的文件,定义一个 ZhihuQustionsSpider 类 继承自 CrawlSpider,这是已经编写好的代码
from scrapy.spiders import Spider
from scrapy.selector import Selector
from scrapy.spiders import Rule, CrawlSpider
from scrapy.linkextractors import LinkExtractor
from zhihu.items import ZhihuQuestionItem
class ZhihuQustionsSpider(CrawlSpider):
name = "zhihu_qustions_spider"
allowed_domains = ["www.zhihu.com"]
start_urls = ['https://www.zhihu.com/topic/19571921/top-answers?page=1']
rules = (Rule(
LinkExtractor(
allow=(r'https://www\.zhihu\.com/topic/19571921/top-answers\?page=\d{2}$')),
callback='parse_item',
follow=True), )
def parse_item(self, response):
selector = Selector(response)
item = ZhihuQuestionItem()
question_name = selector.xpath(
'//a[@class="question_link"][1]/text()').extract()
question_url = selector.xpath(
'//a[@class="question_link"][1]/@href').extract()
best_answer_author = selector.xpath(
'//a[@class="author-link"][1]/text()').extract()
best_answer_summary = selector.xpath(
'//div[@class="zh-summary summary clearfix"][1]/text()').extract()
item['question_name'] = [n for n in question_name]
item['best_answer_author'] = [n for n in best_answer_author]
item['question_url'] = [
'https://www.zhihu.com' + n for n in question_url]
item['best_answer_summary'] = [n for n in best_answer_summary]
#print (item)
yield item
name 是爬虫名字,后面会用到
allowed_domains 是允许爬的域名
start_urls 是开始爬的地址
rules 定义什么样的链接是我们需要接着爬的,里面的 callback 就是我们的解析函数
parse_item 是我们解析重要的函数,这里我使用 xpath 解析,不了解可以去网上找教程学习下,里面的元素信息可以通过chrome的开发者调试模式拿到。
items.py
import scrapy
class ZhihuQuestionItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
question_name = scrapy.Field()
question_url = scrapy.Field()
best_answer_author = scrapy.Field()
best_answer_summary = scrapy.Field()
pass
**pipelines.py **
import codecs
import json
class ZhihuPipeline(object):
def __init__(self):
self.file = codecs.open('zhihu_qustions.txt',
mode='wb', encoding='utf-8')
def process_item(self, item, spider):
line = ''
for i in range(len(item['question_name'])):
question_name = {'question_name': str(
item['question_name'][i]).replace('\n', '')}
try:
question_url = {'question_url': item['question_url'][i]}
except IndexError:
question_url = {'question_url': ""}
try:
best_answer_author = {'best_answer_author': item['best_answer_author'][i]}
except IndexError:
best_answer_author = {'best_answer_author': ""}
try:
best_answer_summary = {'best_answer_summary': str(
item['best_answer_summary'][i]).replace('\n', '')}
except IndexError:
best_answer_summary = {'best_answer_summary': ""}
line = line + json.dumps(question_name, ensure_ascii=False)
line = line + json.dumps(best_answer_author, ensure_ascii=False)
line = line + json.dumps(best_answer_summary, ensure_ascii=False)
line = line + json.dumps(question_url, ensure_ascii=False) + '\n'
self.file.write(line)
def close_spider(self, spider):
self.file.close()
初始化打开一个文件,然后在数据处理函数 process_item 转成 json 写到文件里面。
settings.py 加上以下这些
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
ITEM_PIPELINES = {
'zhihu.pipelines.ZhihuPipeline': 300,
}
DOWNLOAD_DELAY = 1
DOWNLOAD_DELAY 是指每个链接请求的间隔,可以避免太频繁的调用被封。
运行
在工程目录执行
scrapy crawl zhihu_qustions_spider
如果正常的话,就会生成 zhihu_qustions.txt 文件,大概是这样的
源码我我就不传GitHub了,上面基本都包括了