Scrapy
Scrapy,Python开发的一个快速、高层次的屏幕抓取和web抓取框架,用于抓取web站点并从页面中提取结构化的数据。Scrapy用途广泛,可以用于数据挖掘、监测和自动化测试。
Scrapy吸引人的地方在于它是一个框架,任何人都可以根据需求方便的修改。它也提供了多种类型爬虫的基类,如BaseSpider、sitemap爬虫等,最新版本又提供了web2.0爬虫的支持。
crawlspider
crawlspider为scrapy中spider的派生类。可以说是专门为全站爬虫所生。通过命令行生成
scrapy genspider -t crawl spidername url
现在爬取的是腾讯招聘页面的所有信息
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from tenxun.items import ScrapyspidertestItem,infoItem
class Tenxun2Spider(CrawlSpider):
name = 'tenxun2'
allowed_domains = ['hr.tencent.com']
start_urls = ['https://hr.tencent.com/position.php?keywords=&tid=0'] # 初始爬取的链接
base_url = "https://hr.tencent.com/"
rules = (
Rule(LinkExtractor(allow=r'position.php?keywords=&tid=0&start=d+#a'),callback='parse_item',follow=True),# 爬取列表页的其他链接
Rule(LinkExtractor(allow=r'position_detail.php?id=d+&keywords=&tid=d+&lid=d+'), callback='parse_info', follow=False)# 爬取详细页的链接
)
def parse_info(self,response):
'''解析详情页的信息,获取工作职责,工作要求'''
item = infoItem()
work_duty_list = response.xpath('//tr[3]//li/text()').extract()
work_require_list = response.xpath('//tr[4]//li/text()').extract()
item['result_Duties'] = ''.join(work_duty_list)
item['result_Claim'] = ''.join(work_require_list)
yield item
def parse_item(self, response):
'''解析列表页的页面信息'''
result_list = response.xpath("//tr[@class='even']| //tr[@class='odd']")
for node_obj in result_list:
item = ScrapyspidertestItem()
item['result_name'] = node_obj.xpath('.//a/text()').extract_first()
item['result_url'] = 'https://hr.tencent.com/' + node_obj.xpath('.//a/@href').extract_first()
item['result_type'] = node_obj.xpath('.//td[2]/text()').extract_first()
item['result_num'] = node_obj.xpath('.//td[3]/text()').extract_first()
item['result_pos'] = node_obj.xpath('.//td[4]/text()').extract_first()
item['result_date'] = node_obj.xpath('.//td[5]/text()').extract_first()
yield item
其他的item,和pipline都可以与原来的配置相同。