
content
-
2023年2月12日发(作者:)text与content的区别
requests对象的get和post⽅法都会返回⼀个Response对象,这个对象⾥⾯存的是服务器返回的所有信息,包括响应头,响应状态码等。
其中返回的⽹页部分会存在.content和.text两个对象中。
两者区别在于,content中间存的是字节码,⽽text中存的是Beautifulsoup根据猜测的编码⽅式将content内容编码成字符串。
直接输出content,会发现前⾯存在b\'这样的标志,这是字节字符串的标志,⽽text是,没有前⾯的b,对于纯ascii码,这两个可以说⼀模⼀
样,对于其他的⽂字,需要正确编码才能正常显⽰。⼤部分情况建议使⽤.text,因为显⽰的是汉字,但有时会显⽰乱码,这时需要
⽤.(\'utf-8\'),中⽂常⽤utf-8和GBK,GB2312等。这样可以⼿⼯选择⽂字编码⽅式。
所以简⽽⾔之,.text是现成的字符串,.content还要编码,但是.text不是所有时候显⽰都正常,这是就需要⽤.content进⾏⼿动编码。
可以举⼏个例⼦看看:
importrequests
frombs4importBeautifulSoup
response=(\'\')
re_text=
re_content=t
print(re_text)
print(type(re_text))
print(re_content)
print(type(re_content))
ng=\'utf-8\'
re_text=
print(re_text)
输出结果为:(下⾯的分割线是⼿动加的)
href=/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/>ç¾åº¦ä¸ä¸ï¼ä½å°±ç¥é link=#0000cc> hidefocus=truesrc=///img/bd_th=270height=129> name=rsv_bpvalue=1> name=wdclass=s_iptvaluemaxlength=255autocomplete=offautofocus=autofocus> value=ç¾åº¦ä¸ä¸class=\"bgs_btn\"autofocus> class=mnav>æ°é»hao123 class=mnav>å°å¾è§é¢è ´´å§ name=tj_loginclass=lb>ç»å½æ´å¤äº§å å³äºç¾åº¦AboutBaidu id=cp>©2017Baidu使ç¨ç¾åº¦åå¿è¯» feedback>æè§åé¦äº¬ICPè¯030173å· b\'rn Compatiblecontent=IE=Edge> href=/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/> xe7x99xbexe5xbaxa6xe4xb8x80xe4xb8x8bxefxbcx8cxe4xbdxa0xe5xb0xb1xe7x9fxa5xe9x81x93 link=#0000cc> hidefocus=truesrc=///img/bd_th=270height=129> name=rsv_bpvalue=1> name=rsv_bpvalue=1> name=wdclass=s_iptvaluemaxlength=255autocomplete=offautofocus=autofocus> value=xe7x99xbexe5xbaxa6xe4xb8x80xe4xb8x8bclass=\"bgs_btn\"autofocus> href=e=tj_trnewsclass=mnav>xe6x96xb0xe9x97xbb class=mnav>hao123xe5x9cxb0xe5x9bxbe name=tj_trvideoclass=mnav>xe8xa7x86xe9xa2x91xe8xb4xb4xe5x90xa7 name=tj_loginclass=lb>xe7x99xbbxe5xbdx95 block;\">xe6x9bxb4xe5xa4x9axe4xbaxa7xe5x93x81 href=>xe5x85xb3xe4xbax8exe7x99xbexe5xbaxa6AboutBaidu id=cp>©2017Baidu href=/duty/>xe4xbdxbfxe7x94xa8xe7x99xbexe5xbaxa6xe5x89x8dxe5xbfx85xe8xafxbb href=/class=cp- feedback>xe6x84x8fxe8xa7x81xe5x8fx8dxe9xa6x88xe4xbaxacICPxe8xafx81030173xe5x8fxb7 src=///img/> href=/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/>百度⼀下,你就知道 link=#0000cc> hidefocus=truesrc=///img/bd_th=270height=129> name=rsv_bpvalue=1> name=wdclass=s_iptvaluemaxlength=255autocomplete=offautofocus=autofocus> value=百度⼀下class=\"bgs_btn\"autofocus>新闻 hao123地图 视频贴吧 href=/bdorz/?login&tpl=mn&u=http%3A%2F%%2f%3fbdorz_come%3d1name=tj_login class=lb>登录更多产品 关于百度AboutBaidu id=cp>©2017Baidu使⽤百度前必读 feedback>意见反馈京ICP证030173号