Python提取URL中code参数报IndexError: list index out of range问题
报错根因
你代码的索引越界由逻辑不匹配导致,具体如下:
- 你用
if code in get_code判断的是单个字符串code是否存在,但后续split操作拆分的是code=子串,两者判断条件完全不一致。 - 你给出的示例URL里,
code确实存在,但全部位于URL编码的嵌套参数中,对应编码内容为%3Dcode,整个原URL明文里根本没有code=子串,执行get_code.split("code=")后得到的列表长度只有1,取索引[1]自然抛出IndexError。
修复方案
推荐用Python内置的URL解析库处理,避免手动拆分的各种边界问题:
from urllib.parse import unquote, parse_qs, urlparse get_code="https://localhost:8080/soieurow/KPP/alksdjfhlkjhekajhf?eowuiro=akleireyi&URL=https%3A%2F%2Flocalhost:8080%2Fmga%2Fsps%2Foauth%2Foauth20%2Fauthorize%3Fresponse_type%3Dcode%26scope%3Dopenid%2Bname%2Bemail%2Bpostal_code%26client_id%3Dthaljlwej%26redirect_uri%3Dhttp%3A%2F%2Faklsdjfhwekdisd.com%3A5006%2Fredirectcode%26nonce%3DQJT8RbymFk%26acrakdjasd%3DD1%26token%3DfkasjfhalskfhlaksjhkL61bqqADtekpH-HE55lZaX2LJH4Ii9diraseufhalksfhl%26correlation_id%3D4102479872341%26support_encryption%3Dsj2aljkadfj3%26state%3Dajk1234" # 解析第一层URL的查询参数,取出嵌套的授权URL first_query = parse_qs(urlparse(get_code).query) nested_auth_url = unquote(first_query.get('URL', [None])[0]) if not nested_auth_url: print("i don't find code") else: # 解析嵌套URL的查询参数,直接取code值 nested_query = parse_qs(urlparse(nested_auth_url).query) code = nested_query.get('code', [None])[0] print("i have code", code) if code else print("i don't find code")
如果你要快速修改原有拆分逻辑,按如下调整即可:
from urllib.parse import unquote get_code="https://localhost:8080/soieurow/KPP/alksdjfhlkjhekajhf?eowuiro=akleireyi&URL=https%3A%2F%2Flocalhost:8080%2Fmga%2Fsps%2Foauth%2Foauth20%2Fauthorize%3Fresponse_type%3Dcode%26scope%3Dopenid%2Bname%2Bemail%2Bpostal_code%26client_id%3Dthaljlwej%26redirect_uri%3Dhttp%3A%2F%2Faklsdjfhwekdisd.com%3A5006%2Fredirectcode%26nonce%3DQJT8RbymFk%26acrakdjasd%3DD1%26token%3DfkasjfhalskfhlaksjhkL61bqqADtekpH-HE55lZaX2LJH4Ii9diraseufhalksfhl%26correlation_id%3D4102479872341%26support_encryption%3Dsj2aljkadfj3%26state%3Dajk1234" code_flag = 'code=' # 先解码整个URL,再判断code=是否存在 decoded_url = unquote(get_code) if code_flag in decoded_url: # 拆分后取&前面的内容,不要固定截取长度,避免参数长度变化出错 code = decoded_url.split(code_flag)[1].split('&')[0] print("i have code", code) else: print("i don't find code")
内容的提问来源于stack exchange,提问作者SKK
相关产品推荐
相关产品推荐

