python爬虫之requests

session

import requests
from lxml import etree

url = "http://www.renren.com/PLogin.do"
headers={
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}
data = {
    'email':'15201442110',
    'password':''
}

session = requests.session()
rsp1 = session.post(url,headers = headers,data =data)
#可获取cookie,此处不需使用
cookie_dict = requests.utils.cookiejar_from_dict(rsp1.cookies)

get_url = "http://www.renren.com/344986903/profile"
#session中会保存cookie
rsp = session.get(get_url, headers=headers)
#获取页面title
html = etree.HTML(rsp.text)
html_title = html.xpath('//title')[0]

#写入文件中,content为byte,text为str均可直接写入,或者将content转换成str再写入
with open('test.html','w',encoding = 'utf-8') as f:
    f.write(rsp.text)

cookie

import requests
#字典转cookiejar
requests.utils.dict_from_cookiejar(cj)
#cookiejar转字典
requests.utils.cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True)

编码问题

  • r.encoding:从HTTP header中猜测的响应内容编码方式,如果header中存在charset字段,说明访问的服务器对它的资源的编码方式是有要求的,可以使用r.encoding来获取。

  • r.apparent_encoding:根据网页内容分析出的编码方式。如果header中不存在charset字段,则认为默认编码为ISO-8859-1,但是这个编码不能解析中文,因此可以用r.apparent_encoding来解码。

import requests
from lxml import etree
url = 'https://www.baidu.com'
headers={
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}
rsp = requests.get(url ,headers = headers)
print(rsp.encoding)
print(rsp.apparent_encoding)
html = etree.HTML(rsp.text)

#print(html.xpath('//meta/@charset'))
for item in html.xpath('//meta[@http-equiv="Content-Type"]'):
    content_list = item.xpath('./@content')[0]
    print(content_list.split(';'))
    for tmp in content_list.split(';'):
        if 'charset' in tmp:
            print(tmp[8:])
    

content与text

  • text返回的是处理过的Unicode型的数据(据设置的encoding来解码)
  • r.content返回的是bytes型的原始数据。
  • 也就是说,r.content相对于r.text来说节省了计算资源,r.content是把内容bytes返回. 而r.text是decode成Unicode. 如果headers没有charset字符集的化,text()会调用chardet来计算字符集。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值