使用scrapy做數(shù)據(jù)爬取時,尤其是多頁多內(nèi)容爬取桩撮,不能對文件做頻繁執(zhí)行敦第,一是容易被封ip峰弹,二是太頻繁的操作會引起網(wǎng)絡(luò)維護(hù)人員反感。這時芜果,就需要單獨(dú)寫個文件對一些沒有把握的字段進(jìn)行爬取鞠呈,為scrapy多文件爬取服務(wù)。
以拉勾網(wǎng)為例师幕,想要在這個輔助測試的文件中獲得任職的學(xué)歷要求
代碼為:
#coding:utf-8
import requests
import lxml.etree
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36"
}
data = requests.get("https://www.lagou.com/jobs/4680072.html", headers=headers).content.decode("utf-8")
res = lxml.etree.HTML(data)
degree_need = res.xpath("http://*[@class=\"job_request\"]/p/span[4]/text()")
print(degree_need)
代碼中.content.decode("utf-8")與.text等價粟按,requests的content與text的區(qū)別是,content返回的是<class 'bytes'>霹粥,text返回的是<class 'str'>灭将,content.decode("utf-8")返回的是<class 'str'>
上面的解析方式是單頁測試的一種,下面這種和scrapyresponse自己的解析基本一致后控。以后在做單頁測試時庙曙,可以采用這種方式。
#coding:utf-8
import requests
from scrapy.selector import Selector
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36"
}
data = requests.get("https://www.lagou.com/jobs/4680072.html", headers=headers)
selector = Selector(text=data.text)
salary = selector.css(".salary::text").extract_first()
print(salary)