【问题标题】:Issues with invalid syntax error in a urlurl 中存在无效语法错误的问题
【发布时间】:2024-05-17 18:25:02
【问题描述】:

在我的代码中,我试图让用户登录并检索一些信息,但我的变量用户和密码出现语法错误。粗体字在代码中被注释掉

import urllib.request
import time
import pycurl
#Log in
user = input('Please enter your EoBot.com email: ')
password = input('Please enter your password: ')
#gets user ID number
c = pycurl.Curl()
#Error below this line with "user" and "password"
c.setopt(c.URL, "https://www.eobot.com/api.aspx?email="user"&password="password")
c.perform()

【问题讨论】:

    标签: python variables url syntax pycurl


    【解决方案1】:

    您必须通过加倍(或也使用单引号)来转义字符串中的双引号字符:

    c.setopt(c.URL, "https://www.eobot.com/api.aspx?email=""user""&password=""password""")
    

    但实际上它必须是这样的:

    from urllib import parse
    
    # ...
    # your code
    # ...
    
    url = 'https://www.eobot.com/api.aspx?email={}&password={}'.format(parse.quote(user), parse.quote(password))
    c.setopt(c.URL, url)
    

    此服务不希望您在 uri 中发送报价。但特殊字符(如 '@')必须通过 'urllib.parse' 类中的 'quote' 或 'urlencode' 方法进行 url 编码

    【讨论】:

    • 我喜欢这种方法用于我的项目,非常感谢。现在,如果我想使用数字而不是单词,我仍然会使用 .quote 还是其他东西
    • @user3897196,好吧.. 数字 url-encoding 并不是真正需要的(有注意编码),所以你可以跳过它。
    【解决方案2】:

    你需要在字符串内转义你的引号,或者在外面使用单引号。

    c.setopt(c.URL, 'https://www.eobot.com/api.aspx?email="user"&password="password"')
    

    【讨论】:

      【解决方案3】:

      不。重新开始。

      import urllib.parse
      
       ...
      
      qs = urllib.parse.urlencode((('email', user), ('password', password)))
      url = urllib.parse.urlunparse(('https', 'www.eobot.com', 'api.aspx', '', qs, ''))
      c.setopt(c.URL, url)
      

      【讨论】: