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 ...
随机推荐
- GetLastError 错误返回码
(0)-操作成功完成.(1)-功能错误.(2)- 系统找不到指定的文件.(3)-系统找不到指定的路径.(4)-系统无法打开文件.(5)-拒绝访问.(6)-句柄无 效.(7)-存储控制块被损坏.(8)- ...
- Python的魔术方法总结
魔术方法:再不需要程序员定义,本身就存在类中的方法就是魔术方法. 魔术方法通常都长这样:__名字__. 1.__str__和__repr__ 为了方便记忆看如下列子 class Course: def ...
- Java 访问限制符 在同一包中或在不同包中:使用类创建对象的权限 & 对象访问成员变量与方法的权限 & 继承的权限 & 深入理解protected权限
一.实例成员与类成员 1. 当类的字节码被加载到内存, 类中类变量.类方法即被分配了相应内存空间.入口地址(所有对象共享). 2. 当该类创建对象后,类中实例变量被分配内存(不同对象的实例变量互不相同 ...
- AStar算法()
把网上的AStar算法的论述自己实现了一遍,一开始只是最基础的实现.当然,现在AStar算法已经演变出了各种优化的版本,这篇也会基于各种优化不断的更新. 如果对算法不熟悉可以看下Stanford的这篇 ...
- d3js可视化策略
d3js是数据驱动图形的思路.基本可以这么理解,有什么样的图形,后面基本就有类似结构的数据.大概思路步骤如下: 一.适配数据格式 这一步主要是为第二部服务,第一步的结果作为第二部的入参. 比如,画层级 ...
- DevExpress VCL Controls 2019发展路线图(No.2)
[DevExpress VCL Controls下载] ExpressQuantumTreeList Excel-inspired Filter (v19.1) 与ExpressQuantumGrid ...
- ForkJoinPool 源码
ForkJoinPool----FJP先看task.fork方法,含义是将当前任务,放到当前线程的工作队列中.但是第一次执行这个方法是在主线程中,主线程是不可能被FJP管理的.那么就进入ForkJoi ...
- Java中的公平锁和非公平锁实现详解
前言 Java语言中有许多原生线程安全的数据结构,比如ArrayBlockingQueue.CopyOnWriteArrayList.LinkedBlockingQueue,它们线程安全的实现方式并非 ...
- Web开发常见的几个漏洞解决方法 (转)
基本上,参加的安全测试(渗透测试)的网站,可能或多或少存在下面几个漏洞:SQL注入漏洞.跨站脚本攻击漏洞.登陆后台管理页面.IIS短文件/文件夹漏洞.系统敏感信息泄露. 1.测试的步骤及内容 这些安全 ...
- ajax请求,函数外无法获取请求的数据问题解决
一.开发中遇到需要通过ajax请求获取其他函数能否执行的状态,但是当赋值给statusFlag时发现无法赋值:ajax请求默认为异步的方式,该请求的操作被放置在任务队列中,并不会按顺序执行,所以被赋值 ...