本文实例为爬取拉勾网上的python相关的职位信息, 这些信息在职位详情页上, 如职位名, 薪资, 公司名等等.
分析思路
分析查询结果页
在拉勾网搜索框中搜索'python'关键字, 在浏览器地址栏可以看到搜索结果页的url为: 'https://pany_div.xpath('./dd//li[4]/h4[@class="c_feature_name"]/text()').extract_first() yield item
编写middlewares.py, 自定义downloadermiddleware, 用来每次发送请求前, 随机设置user-agent, 这里使用了第三方库 fake_useragent, 能够随机提供user-agent, 使用前先安装: pip install fake_useragent
from fake_useragent import UserAgentimport randomclass RandomUserAgentDM: """ 随机获取userAgent """ def __init__(self): self.user_agent = UserAgent() def process_request(self, request, spider): request.headers['User-Agent'] = self.user_agent.random编写pipelines.py, 将数据存为json文件
import jsonclass LagouPipeline: def process_item(self, item, spider): with open('jobs.json', 'a', encoding='utf-8') as f: item_json = json.dumps(dict(item), ensure_ascii=False, indent=2) f.write(item_json) f.write('\n')编写settings.py
# 设置日志显示LOG_LEVEL = 'WARNING'# 设置ROBOTSTXT协议, 若为true则不能爬取数据ROBOTSTXT_OBEY = False# 设置下载器延迟, 反爬虫的一种策略DOWNLOAD_DELAY = 0.25# 开启DOWNLOADER_MIDDLEWARESDOWNLOADER_MIDDLEWARES = { # 'LaGou.middlewares.LagouDownloaderMiddleware': 543, 'LaGou.middlewares.RandomUserAgentDM' :100,}# 开启ITEM_PIPELINESITEM_PIPELINES = { 'LaGou.pipelines.LagouPipeline': 300,}启动爬虫
scrapy crawl lagou
发现依然只能5 6页, 说明拉勾网的反爬确实做得比较好, 还可以继续通过使用代理来进行反反爬, 这里就不再演示了,
查看爬取结果
以上就是Python爬虫实例——scrapy框架爬取拉勾网招聘信息的详细内容,更多关于Python爬虫爬取招聘信息的资料请关注其它相关文章!