爬虫琐碎知识【Cookie、requests、编码方式问题】

Cookie

1.在cookie登陆的过程中,有两种方法,第一种是直接从chrome中获取request-headers,第二种是导入 cookieJar进行登陆,创建一个handler,用handler去创建一个opener进行操作。

from urllib import request
from http.cookiejar import CookieJar
cookiejar = CookieJar()
handler = requests.HTTPCookieProcessor(cookiejar)
opener = request.build_opener(handler)

requests

1.在使用requests库的时候,text与content同时返回的数据类型是不同的(text返回Unicode,content返回字节流),一般默认text就行,但是出现乱码的时候就需要content指定解码了。

import requests
response = requests.get('https:\\www.baidu.com\')
print(response.content.decode('utf-8'))

2.发送post请求。直接调用requests.post方法就行,如果返回的事json数据,可以调用response.json()转换成字典或者列表。

3.requests在使用IP代理时候的源码。尽量选择高匿名的代理IP,而非透明的。

import requests

proxy = {
    'http':'121.237.149.71:3000'
}
response = requests.get('http://httpbin.org/ip',proxies=proxy)

print(response.text)

编码方式问题

import requests
response = requests.get('url')
response.encoding = response.apparent_encoding
这样可以解决99.99%的乱码
爬取网页中
response.encoding:如果header中不存在charset,则默认编码为ISO-8859-1
而response.apparent_encoding他是一个备用编码方式,他会根据内容自动匹配给你个合适的编码方式
那为什么只能99.99%而不是100%解决,还有可能就是网站开发者故意放2种编码进去隐藏一些重要信息
但是这样跑程序会非常慢所以还是直接指定编码方式的好一些
recipe_response = requests.get(href,headers=headers)
recipe_response.encoding='utf-8'
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值