Request、Response
Request
Request对象在我们写爬虫发送请求的时候调用,参数如下:
url: 就是需要请求的urlcallback: 指定该请求返回的Response由那个函数来处理。method: 请求方法,默认GET方法,可设置为"GET", "POST", "PUT"等,且保证字符串大写headers: 请求时,包含的头文件。一般不需要。内容一般如下:Host: media.readthedocs.org
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0
Accept: text/css,/;q=0.1
Accept-Language: zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Cookie: _ga=GA1.2.1612165614.1415584110;
Connection: keep-alive
If-Modified-Since: Mon, 25 Aug 2014 21:59:35
GMT Cache-Control: max-age=0
meta: 在不同的解析函数之间传递数据使用的。字典dict型# -*- coding: utf-8 -*-
import scrapy
from TencentHR.items import TencenthrItem
class HrSpider(scrapy.Spider):
name = 'hr'
# allowed_domains = ['ddd']
start_urls = ['https://hr.tencent.com/position.php']
def parse(self, response):
trs = response.xpath('//table[@class="tablelist"]/tr[@class="odd"] | //table[@class="tablelist"]/tr[@class="even"]')
# print(len(trs))
for tr in trs:
items = TencenthrItem()
detail_url = tr.xpath('./td/a/@href').extract()[0]
items['position_name'] = tr.xpath('./td/a/text()').extract()[0]
try:
items['position_type'] = tr.xpath('./td[2]/text()').extract()[0]
except:
print("{}职位没有类型,url为{}".format(items['position_name'], "https://hr.tencent.com/" + detail_url))
items['position_type'] = None
items['position_num'] = tr.xpath('./td[3]/text()').extract()[0]
items['publish_time'] = tr.xpath('./td[5]/text()').extract()[0]
items['work_addr'] = tr.xpath('./td[4]/text()').extract()[0]
detail_url = 'https://hr.tencent.com/' + detail_url
yield scrapy.Request(detail_url,
comallback=self.parse_detail,
meta={"items":items}
)
next_url = response.xpath('//a[text()="下一页"]/@href').extract_first()
next_url = 'https://hr.tencent.com/' + next_url
print(next_url)
yield scrapy.Request(next_url,
callback=self.parse
)
def parse_detail(self,response):
items = response.meta['items']
items["work_duty"] = response.xpath('//table[@class="tablelist textl"]/tr[3]//li/text()').extract()
items["work_require"] =response.xpath('//table[@class="tablelist textl"]/tr[4]//li/text()').extract()
yield itemsencoding: 使用默认的 'utf-8' 就行。dont_filter: 表明该请求不由调度器过滤。这是当你想使用多次执行相同的请求,忽略重复的过滤器。默认为False。errback: 指定错误处理函数
Response
Response属性和可以调用的方法
meta: 从其他解析函数传递过来的meta属性,可以保持多个解析函数之间的数据连接encoding: 返回当前字符串编码和编码的格式text: 返回Unicode字符串body: 返回bytes字符串xpath: 可以调用xpath方法解析数据css: 调用css选择器解析数据
发送POST请求
当我们需要发送Post请求的时候,就调用Request中的子类
FormRequest来实现,如果需要在爬虫一开始的时候就发送post请求,那么需要在爬虫类中重写start_requests(self)方法, 并且不再调用start_urls中的url案例 登录豆瓣网
# -*- coding: utf-8 -*-
import scrapy
class TestSpider(scrapy.Spider):
name = 'login'
allowed_domains = ['www.douban.com']
# start_urls = ['http://www.baidu.com/']
def start_requests(self):
login_url = "https://accounts.douban.com/j/mobile/login/basic"
headers = {
'Referer': 'https://accounts.douban.com/passport/login_popup?login_source=anony',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'
}
formdata = {
'ck': '',
'name': 用户名,
'password': 密码,
'remember': 'true',
'ticket': ''
}
request = scrapy.FormRequest(login_url, callback=self.parse, formdata=formdata, headers=headers)
yield request
def parse(self, response):
print(response.text)返回结果,可以看到登录成功了
{"status":"success","message":"success","description":"处理成功","payload":{"account_info":{"name":"仅此而已","weixin_binded":false,"phone":"手机号","avatar":{"medium":"https://img3.doubanio.com\/icon\/user_large.jpg","median":"https://img1.doubanio.com\/icon\/user_normal.jpg","large":"https://img3.doubanio.com\/icon\/user_large.jpg","raw":"https://img3.doubanio.com\/icon\/user_large.jpg","small":"https://img1.doubanio.com\/icon\/user_normal.jpg","icon":"https://img3.doubanio.com\/pics\/icon\/user_icon.jpg"},"id":"193317985","uid":"193317985"}}}登录成功之后请求个人主页,可以看到我们可以访问登录之后的页面了
# -*- coding: utf-8 -*-
import scrapy class TestSpider(scrapy.Spider):
name = 'login'
allowed_domains = ['www.douban.com']
# start_urls = ['http://www.baidu.com/'] def start_requests(self):
login_url = "https://accounts.douban.com/j/mobile/login/basic"
headers = {
'Referer': 'https://accounts.douban.com/passport/login_popup?login_source=anony',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'
}
formdata = {
'ck': '',
'name': 用户名,
'password': 密码,
'remember': 'true',
'ticket': ''
}
request = scrapy.FormRequest(login_url, callback=self.parse, formdata=formdata, headers=headers)
yield request def parse(self, response):
print(response.text)
# 登录成功之后访问个人主页
url = "https://www.douban.com/people/193317985/"
yield scrapy.Request(url=url, callback=self.parse_detail) def parse_detail(self, response):
print(response.text)
Request、Response的更多相关文章
- Request 、Response 与Server的使用
纯属记录总结,以下图片都是来自 ASP.NET笔记之 Request .Response 与Server的使用 Request Response Server 关于Server.MapPath 方法看 ...
- LoadRunner中取Request、Response
LoadRunner中取Request.Response LoadRunner两个“内置变量”: 1.REQUEST,用于提取完整的请求头信息. 2.RESPONSE,用于提取完整的响应头信息. 响应 ...
- struts2中获取request、response,与android客户端进行交互(文件传递给客户端)
用struts2作为服务器框架,与android客户端进行交互需要得到request.response对象. struts2中获取request.response有两种方法. 第一种:利用Servle ...
- 第十五节:HttpContext五大核心对象的使用(Request、Response、Application、Server、Session)
一. 基本认识 1. 简介:HttpContext用于保持单个用户.单个请求的数据,并且数据只在该请求期间保持: 也可以用于保持需要在不同的HttpModules和HttpHandlers之间传递的值 ...
- java web(四):request、response一些用法和文件的上传和下载
上一篇讲了ServletContent.ServletCOnfig.HTTPSession.request.response几个对象的生命周期.作用范围和一些用法.今天通过一个小项目运用这些知识.简单 ...
- @ModelAttribute设置request、response、session对象
利用spring web提供的@ModelAttribute注解 放在类方法的参数前面表示引用Model中的数据 @ModelAttribute放在类方法上面则表示该Action类中的每个请求调用之前 ...
- spring aop 获取request、response对象
在网上看到有不少人说如下方式获取: 1.在web.xml中添加监听 <listener> <listener-class> org. ...
- SpringMvc4中获取request、response对象的方法
springMVC4中获取request和response对象有以下两种简单易用的方法: 1.在control层获取 在control层中获取HttpServletRequest和HttpServle ...
- springboot的junit4模拟request、response对象
关键字: MockHttpRequest.Mock测试 问题: 在模拟junit的request.response对象时,会报如下空指针异常. 处理方法: 可用MockHttpServletReque ...
- 在SpringMVC中操作Session、Request、Response对象
示例 @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper user ...
随机推荐
- vue+uwsgi+nginx部署前后端分离项目
前后端分离,vue前端提供静态页面,且可以向后台发起get,post等restful请求. django后台提供数据支撑,返回json数据,返回给vue,进行数据页面渲染 后端 创建虚拟环境 解决dj ...
- P2010 回文日期 题解
这题其实就是纯暴力,暴力,再暴力,毫无技巧可言(总之您怎么乱搞都不会超时QAQ) 首先,根据题意,我们明白每年自多产生一个回文日期,因为对于每年的三百多天,前四位是固定的. 所以,我们只需要进行一个从 ...
- 如何查看tomcat的支持的jdk、servlet、jsp的版本
解压servlet-api 查看 可以看出,支持的servlet版本是4.0,jdk是1.8
- Linux监控
第三十次课 Linux监控 目录 一. Linux监控平台介绍 二. zabbix监控介绍 三. 安装zabbix 四. 忘记Admin密码如何做 五. 主动模式和被动模式 六. 添加监控主机 七. ...
- SharePoint Framework 基于团队的开发(二)
博客地址:http://blog.csdn.net/FoxDave 本篇介绍SPFx项目的一般开发流程.SharePoint Framework基于开源的工具链,也遵循开源技术栈中其他项目的开发流程. ...
- foreach 使用 引用& $value . 使用 unset($value)
1.知识点: 2. 例子 2.1 例子1 . $arr 引用循环, 赋值变量是 &$v ,第一个循环使用后 ,没有 使用unset($v) , $arr2 正常循环, 赋值变量是 $v , ...
- django遇到的问题-系列1
django开发中遇到的问题以及解决方法: 1.You called this URL via POST, but the URL doesn't end in a slash and you hav ...
- python命令行运行py文件找不到模块的解决办法
问题: 新建了一个项目,目录结构如下: 然后在pycharm中运行glovar是没有问题的,但是在命令行中运行就会提示找不到init模块 这是因为在pycharm中运行的时候,pycharm会自动将项 ...
- [转载] java并发编程:Lock(线程锁)
作者:海子 原文链接: http://www.cnblogs.com/dolphin0520/p/3923167.html 出处:http://www.cnblogs.com/dolphin0520/ ...
- mysql远程访问1045的问题解决
mysql远程访问1045的问题解决 首先进入mysql数据库,然后输入下面两个命令 grant all privileges on *.* to 'root'@'%' identified by ' ...