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来计算字符集。