有关URL中无效语法错误的问题

0 投票
3 回答
9129 浏览
提问于 2025-04-18 16:10

在我的代码中,我想让用户登录并获取一些信息,但我在使用变量 user 和 password 时遇到了语法错误。代码中的粗体部分是被注释掉的。

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()

3 个回答

0

你需要在字符串里面把引号进行转义,或者在外面用单引号。

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

不行,重新来过。

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)
0

在字符串中,如果你想使用双引号,就得把它们变成两个双引号(或者用单引号也可以):

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)

这个服务不希望你在网址中发送引号。不过,像'@'这样的特殊字符必须通过'quote'或'urlencode'方法进行网址编码,这些方法来自'urllib.parse'这个类。

撰写回答