错误收集

C:\Users\Administrator\PycharmProjects\PythonProject2\.venv\Scripts\python.exe C:\Users\Administrator\PycharmProjects\PythonProject2\cookie_test.py 
{'success': True, 'state': 1, 'message': '响应成功', 'content': {'access_token': 'bf5a680c-9895-4d55-b49b-34f51b0268e3', 'user_id': 100030011, 'user': {'id': 100030011, 'name': '15321919666', 'portrait': 'https://edu-lagou.oss-cn-beijing.aliyuncs.com/images/2020/06/28/15933251448762927.png', 'phone': '15321919666', 'password': '123456', 'reg_ip': None, 'account_non_expired': None, 'credentials_non_expired': None, 'account_non_locked': None, 'status': 'DISABLE', 'is_del': None, 'createTime': 1594347555000, 'updateTime': 1594347555000}}}
 登录接口中的cookie:  <RequestsCookieJar[<Cookie JSESSIONID=A3FFBD48812FEEF81B0801430340E636 for www.edu2.com/ssm_web/>, <Cookie JSESSIONID="" for .edu2.com/>]>
json数据转化为字符串 {"success": true, "state": 1, "message": "\u54cd\u5e94\u6210\u529f", "content": {"access_token": "bf5a680c-9895-4d55-b49b-34f51b0268e3", "user_id": 100030011, "user": {"id": 100030011, "name": "15321919666", "portrait": "https://edu-lagou.oss-cn-beijing.aliyuncs.com/images/2020/06/28/15933251448762927.png", "phone": "15321919666", "password": "123456", "reg_ip": null, "account_non_expired": null, "credentials_non_expired": null, "account_non_locked": null, "status": "DISABLE", "is_del": null, "createTime": 1594347555000, "updateTime": 1594347555000}}}
bf5a680c-9895-4d55-b49b-34f51b0268e3
Traceback (most recent call last):
  File "C:\Users\Administrator\PycharmProjects\PythonProject2\cookie_test.py", line 45, in <module>
    re.findall(pattern="'access_token': '(.*?)'",string=result_data_info.content)
  File "D:\Program\Util\py\Lib\re\__init__.py", line 217, in findall
    return _compile(pattern, flags).findall(string)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: cannot use a string pattern on a bytes-like object

错误分析

TypeError: cannot use a string pattern on a bytes-like object   

由上面红色的字体可以看出,使用python中的re模块匹配正则表达式的时候,填入的参数是一个对象,而不是一个字符串。正则表达式匹配需要字符串。

错误解决

使用str()函数将对象转化为字符串类型的

修改代码

# 使用正则表达式提取token
re_token = re.findall(pattern=r"'access_token': '(.*?)'",string=str(result_data_info.json()))

运行结果

对比:

re_token

json_token

数据已经成功提取。并且报错已经成功解决。传递参数的时候应该传递字符串类型,实现传递为对象类型。

更多推荐