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 ...
随机推荐
- redis学习——数据持久化
一.概述 Redis的强大性能很大程度上都是因为所有数据都是存储在内存中的,然而当Redis重启后,所有存储在内存中的数据将会丢失,在很多情况下是无法容忍这样的事情的.所以,我们需要将内存中的数据持久 ...
- Github 搭建 Hexo 纯静态化个人博客平台
以前一直想搭建一个属于自己的博客平台,有余种种原因一直未能实现,最近闲来无事,参照网上的教程,搭建了属于自己的博客.自己的博客网站,样式自由,不需要受限于各大平台. 本篇为从零开始的基础篇,本篇所包含 ...
- Spring _day01_下载、概述、监听器
Spring:SE/EE开发的一站式框架. .一站式框架:有EE开发的每一层解决方案. . WEB层 :SpringMVC . Service层 :Spring的Bean管理,Spring ...
- spring整合redis(哨兵模式)
首先服务器搭建哨兵模式(我这里使用的是Windows8系统),感谢两位博主,少走不少弯路,在此给出链接:服务器哨兵模式搭建和整合哨兵模式 什么一些介绍就不介绍了,可以看一下连接,比较详细,初次接触,当 ...
- @Dependson注解与@ConditionalOnBean注解的区别
@Dependson注解是在另外一个实例创建之后才创建当前实例,也就是,最终两个实例都会创建,只是顺序不一样 @ConditionalOnBean注解是只有当另外一个实例存在时,才创建,否则不创建,也 ...
- linux目录说明
/etc/passwd 用户信息文件 [root@web01 ~]# cat /etc/passwd root: x: : : root: /root: /bin/bash 可登录用户 bin: x ...
- table-layout:fixed; 表格比例固定
固定表格布局: 固定表格布局与自动表格布局相比,允许浏览器更快地对表格进行布局. 在固定表格布局中,水平布局仅取决于表格宽度.列宽度.表格边框宽度.单元格间距,而与单元格的内容无关. 通过使用固定表格 ...
- python笔记24-os模块
import osprint(os.getcwd())#取当前工作目录#os.chmod('/usr/local',7)#给文件目录加权限,7是最高权限print(os.chdir(r"e: ...
- LINUX安装vm tools及使用方法(centos7,vm12)
1.安装vmtools: 下载文件之后,到自动挂在的目录下(/run/media/用户名),将文件cp到其他的目录: 然后到其他的目录,解压缩,执行pl文件,执行方式:./vmware-install ...
- Ceph集群更换public_network网络
1.确保ceph集群是连通状态 这里,可以先把机器配置为以前的x.x.x.x的网络,确保ceph集群是可以通的.这里可以执行下面的命令查看是否连通,显示HEALTH_OK则表示连通 2.获取monma ...