Request

Request对象在我们写爬虫发送请求的时候调用,参数如下:

  • url: 就是需要请求的url

  • callback: 指定该请求返回的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

    • Referer: http://scrapy-chs.readthedocs.org/zh_CN/0.24/

    • 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 items
  • encoding: 使用默认的 '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的更多相关文章

  1. Request 、Response 与Server的使用

    纯属记录总结,以下图片都是来自 ASP.NET笔记之 Request .Response 与Server的使用 Request Response Server 关于Server.MapPath 方法看 ...

  2. LoadRunner中取Request、Response

    LoadRunner中取Request.Response LoadRunner两个“内置变量”: 1.REQUEST,用于提取完整的请求头信息. 2.RESPONSE,用于提取完整的响应头信息. 响应 ...

  3. struts2中获取request、response,与android客户端进行交互(文件传递给客户端)

    用struts2作为服务器框架,与android客户端进行交互需要得到request.response对象. struts2中获取request.response有两种方法. 第一种:利用Servle ...

  4. 第十五节:HttpContext五大核心对象的使用(Request、Response、Application、Server、Session)

    一. 基本认识 1. 简介:HttpContext用于保持单个用户.单个请求的数据,并且数据只在该请求期间保持: 也可以用于保持需要在不同的HttpModules和HttpHandlers之间传递的值 ...

  5. java web(四):request、response一些用法和文件的上传和下载

    上一篇讲了ServletContent.ServletCOnfig.HTTPSession.request.response几个对象的生命周期.作用范围和一些用法.今天通过一个小项目运用这些知识.简单 ...

  6. @ModelAttribute设置request、response、session对象

    利用spring web提供的@ModelAttribute注解 放在类方法的参数前面表示引用Model中的数据 @ModelAttribute放在类方法上面则表示该Action类中的每个请求调用之前 ...

  7. spring aop 获取request、response对象

    在网上看到有不少人说如下方式获取: 1.在web.xml中添加监听 <listener>          <listener-class>              org. ...

  8. SpringMvc4中获取request、response对象的方法

    springMVC4中获取request和response对象有以下两种简单易用的方法: 1.在control层获取 在control层中获取HttpServletRequest和HttpServle ...

  9. springboot的junit4模拟request、response对象

    关键字: MockHttpRequest.Mock测试 问题: 在模拟junit的request.response对象时,会报如下空指针异常. 处理方法: 可用MockHttpServletReque ...

  10. 在SpringMVC中操作Session、Request、Response对象

    示例 @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper user ...

随机推荐

  1. implode() 数组元素组合函数

    定义和用法 implode() 函数把数组元素组合为一个字符串. 语法:implode(separator,array); 说明 虽然 separator 参数是可选的.但是为了向后兼容,推荐您使用使 ...

  2. HTCVIVE定位器更新之后,定位器指示灯不亮,重置基站固件操作指南。

    HTCVIVE定位器更新之后,定位器指示灯不亮,固件修复指南 建议您重置基站固件,操作如下:请您使用手机来拍照运行中基站的“激光发射器”面板,并且数一下是否有17颗LED灯,如果没有17颗,则基本可以 ...

  3. Django REST framework---请求和响应

    Django REST framework---请求和响应 [Request对象] 概念: 平时我们在写Django的视图函数的时候,都会带上一个request参数,这样就能处理平时搭建网站时,浏览器 ...

  4. 正则表达式中的re.S

    正则表达式中,“.”的作用是匹配除“\n”以外的任何字符,也就是说,它是在一行中进行匹配.这里的“行”是以“\n”进行区分的.a字符串有每行的末尾有一个“\n”,不过它不可见. 如果不使用re.S参数 ...

  5. sqoop碰到的问题

    sqoop碰到的问题 背景:从Oracle接入数据,一张表一千多万,数据量13G左右. 报错,表名找不到,将表名改成大写的 Exception in thread "main" j ...

  6. 用几句话说一说CMake add_dependencies & target_link_libraries的使用区别

    简单说一说前两天学习使用CMake解决链接问题时遇到的一个问题. 对于编译时遇到的依赖问题,很多时候我们只需要一句target_link_libraries就可以搞定. 但是CMake还有另外一个co ...

  7. (转) java 通过 jdbc 链接 ms sql server 中出现 "no suitable driver for ..."

    原文连接 : http://blog.csdn.net/stewen_001/article/details/19553173/ 前面是 基本操作步骤,按照原博主的方式进行操作即可...() 这里是需 ...

  8. 自动化运维之ansible

    第三十九课 自动化运维之ansible 目录 十五. ansible介绍 十六. ansible安装 十七. ansible远程执行命令 十八. ansible拷贝文件或目录 十九. ansible远 ...

  9. C++笔记之关键字explicit

    在C++中,explicit关键字用来修饰类的构造函数,被修饰的构造函数的类,不能发生相应的隐式类型转换,只能以显示的方式进行类型转换. explicit使用注意事项: explicit 关键字只能用 ...

  10. shell中特殊位置参数变量

    shell中特殊位置参数变量:$0.$n.$#.$*.$@ $0:获取当前执行shell脚本文件名,如果执行脚本包含路径,那么就包括脚本路径 $n:获取当前执行shell脚本的第n个参数值.n=1.. ...