简体   繁体   English

使用'pass'作为字典关键字

[英]Use 'pass' as a dictionary keyword

I'm trying to make a fairly basic requests script which signs into a website, however I'm running into a problem; 我正在尝试制作一个相当基本的请求脚本,它会登录到一个网站,但是我遇到了一个问题; the website requires the 'pass' key, however whenever I try to use this python throws an error saying invalid syntax. 网站需要'pass'键,但是每当我尝试使用这个python时都会抛出一个错误,说明语法无效。 Here's my code: 这是我的代码:

import requests

with requests.Session() as c:
    url = 'www.a_url.com'
    USERNAME = 'a username'
    PASSWORD = 'a password'
    c.get(url)
    login_data = dict(user=USERNAME, pass=PASSWORD, jsok='1', dologin='Login')
    c.post(url, data=login_data, headers={"Referer": 'www.a_referer.com'})
    page = c.get('www.a_page.com')
    print(page.content)
    output = open('test.html','w')
    output.write(str(page.content))

And the error I'm given is: 我给出的错误是:

    login_data = dict(user=USERNAME, pass=PASSWORD, jsok='1', dologin='Login')
                                        ^
SyntaxError: invalid syntax

Any idea how I can force python to ignore the 'pass' and just use it as the dict key? 知道如何强制python忽略'pass'并将其用作dict键吗?

Since pass is a keyword, it can't be used as an identifier. 由于pass是关键字,因此不能用作标识符。 You'll need to use a dict-literal for this: 你需要使用dict-literal:

login_data = {
    'user': USERNAME,
    'pass': PASSWORD,
    'jsok': '1',
    'dologin': 'Login',
}

Short answer, you cannot do so in that syntax. 简短的回答,你不能用那种语法来做。 pass is a reserved keyword for python, such as return . pass是python的保留关键字,例如return

The alternative way of setting arbitrary object as key is to use this syntax: 将任意对象设置为键的另一种方法是使用以下语法:

login_data = {"user": USERNAME, "pass": PASSWORD, ...}

This is more generic and you can use anything as key. 这是更通用的,你可以使用任何东西作为关键。

{None: 1, 1: 2, str: int}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM