2021SC@SDUSC
ECommerceCrawlers项目分析(十二)
目录
一、ZhaopinCrawler
招聘文件夹下的爬取已经分析完,下面是自己额外的学习过程Scrapy框架爬取—>>>腾讯招聘的所有职位信息
1、先分析腾讯招聘网站url
第一页:https://hr.tencent.com/position.php?&start=0#a
第二页:https://hr.tencent.com/position.php?&start=10#a
第三页:https://hr.tencent.com/position.php?&start=20#a
发现有的职位类别为空,所有在找职位类别的时候空值也要加进去,否则for循环取不到值会直接退出了 ./td[2]/text()|./td[2]
2、目录结构
3、代码
items.py
# -*- coding: utf-8 -*-import scrapy
class TencentItem(scrapy.Item):
# 职位名
positionname = scrapy.Field()
# 详情连接
positionlink = scrapy.Field()
# 职位类别
positionType = scrapy.Field()
# 招聘人数
peopleNum = scrapy.Field()
# 工作地点
workLocation = scrapy.Field()
# 发布时间
publishTime = scrapy.Field()
tencentPosition.py
# -*- coding: utf-8 -*-
import scrapy
from tencent.items import TencentItem
class TencentpositionSpider(scrapy.Spider):
name = "tencent"
allowed_domains = ["tencent.com"]
url = "http://hr.tencent.com/position.php?&start="
offset = 0
start_urls = [url + str(offset)]
def parse(self, response):
for each in response.xpath("//tr[@class='even'] | //tr[@class='odd']"):
# 初始化模型对象
item = TencentItem()
# 职位名称
item['positionname'] = each.xpath("./td[1]/a/text()").extract()[0]
# 详情连接
item['positionlink'] = each.xpath("./td[1]/a/@href").extract()[0]
# 职位类别
item['positionType'] = each.xpath("./td[2]/text()|./td[2]").extract()[0]
# 招聘人数
item['peopleNum'] = each.xpath("./td[3]/text()").extract()[0]
# 工作地点
item['workLocation'] = each.xpath("./td[4]/text()").extract()[0]
# 发布时间
item['publishTime'] = each.xpath("./td[5]/text()").extract()[0]
yield item
if self.offset < 3171:
self.offset += 10
# 每次处理完一页的数据之后,重新发送下一页页面请求
# self.offset自增10,同时拼接为新的url,并调用回调函数self.parse处理Response
yield scrapy.Request(self.url + str(self.offset), callback = self.parse)
pipelines.py
# -*- coding: utf-8 -*-
import json
class TencentPipeline(object):
def __init__(self):
self.filename = open("tencent.json", "w")
def process_item(self, item, spider):
text = json.dumps(dict(item), ensure_ascii = False) + ",\n"
self.filename.write(text.encode("utf-8"))
return item
def close_spider(self, spider):
self.filename.close()
settings.py里面的设置
ROBOTSTXT_OBEY = True
DOWNLOAD_DELAY = 4 #防止爬取过快丢失数据
DEFAULT_REQUEST_HEADERS = {
"User-Agent" : "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;",
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
}
ITEM_PIPELINES = {
'tencent.pipelines.TencentPipeline': 300,
}
4、结果
二、Handler和Opener介绍
Handler处理器和自定义Opener
opener是urllib2.OpenerDirector的实例,我们之前一直在使用urlopen,它是一个特殊的opener(也就是我们构建好的)。
但是urlopen()方法不支持代理、cookie等其他的HTTP/GTTPS高级功能。所有要支持这些功能:
1.使用相关的Handler处理器来创建特定功能的处理器对象;
2.然后通过urllib2.build_opener()方法使用这些处理器对象,创建自定义opener对象;
3.使用自定义的opener对象,调用open()方法发送请求。
如果程序里所有的请求都使用自定义的opener,可以使用urllib2.install_open()将自定义的opener对象定义为全局opener,表示如果之后凡是调用urlopen,都将使用这个opener(根据自己的需求来选择)
简单的自定义opener()
# _*_ coding:utf-8 _*_
import urllib2
# 构建一个HTTPHandler处理器对象,支持处理HTTP的请求
http_handler = urllib2.HTTPHandler()
# 调用build_opener()方法构建一个自定义的opener对象,参数是构建的处理器对象
opener = urllib2.build_opener(http_handler)
request = urllib2.Request('http://www.baidu.com/s')
# 调用自定义opener对象的open()方法,发送request请求response = opener.open(request) print response.read()
debug log模式
import urllib2
# 构建一个HTTPHandler处理器对象,支持处理HTTP的请求
# http_handler = urllib2.HTTPHandler()
# 主要用于调试用
http_handler = urllib2.HTTPHandler(debuglevel=1)
# 调用build_opener()方法构建一个自定义的opener对象,参数是构建的处理器对象
opener = urllib2.build_opener(http_handler)
request = urllib2.Request('http://www.baidu.com/s')
response = opener.open(request)
# print response.read()
ProxyHandler处理器(代理设置)
使用代理IP,这是爬虫/反爬虫的第二大招,通常也是最好用的。
很多网站会检测某一段时间某个IP的访问次数(通过流量统计,系统日志等),如果访问次数多的不像正常人,它会禁止这个IP的访问。
所以我们可以设置一些代理服务器,每隔一段时间换一个代理,就算IP被禁止,依然可以换个IP继续爬取。
urllib2中通过ProxyHandler来设置使用代理服务器,使用自定义opener来使用代理:
免费代理网站:http://www.xicidaili.com/;https://www.kuaidaili.com/free/inha/
# _*_ coding:utf-8 _*_
import urllib2
# 构建一个Handler处理器对象,参数是一个字典类型,包括代理类型和代理服务器IP+Port
httpproxy_handler = urllib2.ProxyHandler({'http':'118.114.77.47:8080'})
#使用代理
opener = urllib2.build_opener(httpproxy_handler)
request = urllib2.Request('http://www.baidu.com/s')
#1 如果这么写,只有使用opener.open()方法发送请求才使用自定义的代理,而urlopen()则不使用自定义代理。
response = opener.open(request)
#12如果这么写,就是将opener应用到全局,之后所有的,不管是opener.open()还是urlopen() 发送请求,都将使用自定义代理。
#urllib2.install_opener(opener)
#response = urllib2.urlopen(request)
print response.read()
但是,这些免费开放代理一般会有很多人都在使用,而且代理有寿命短,速度慢,匿名度不高,HTTP/HTTPS支持不稳定等缺点
参考:https://www.cnblogs.com/derek1184405959/p/8449159.html