我怎样才能将这个符号视为文本?

How can I treat this ampersand as text?

from googlefinance import getQuotes

print(getQuotes("NSE:M\&MFIN"),)

& 符号被视为代码,但我想将其视为文本;我收到一个错误的请求异常:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/.../site-packages/googlefinance/__init__.py", line 70, in getQuotes
    content = json.loads(request(symbols))
  File "/.../site-packages/googlefinance/__init__.py", line 33, in request
    resp = urlopen(req)
  File "/.../urllib/request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "/.../urllib/request.py", line 532, in open
    response = meth(req, response)
  File "/.../urllib/request.py", line 642, in http_response
    'http', request, response, code, msg, hdrs)
  File "/.../urllib/request.py", line 570, in error
    return self._call_chain(*args)
  File "/.../urllib/request.py", line 504, in _call_chain
    result = func(*args)
  File "/.../urllib/request.py", line 650, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: Bad Request

我试图逃避它(使用 \)但这也没有用。

如何将这个 & 符号视为文本?

该库相当幼稚,因为它只是将符号附加到 URL 而没有正确编码,请参阅 the source code:

def buildUrl(symbols):
    symbol_list = ','.join([symbol for symbol in symbols])
    # a deprecated but still active & correct api
    return 'http://finance.google.com/finance/info?client=ig&q=' \
        + symbol_list

您可以使用 urllib.parse.quote() function:

手动预先引用来解决此问题
from urllib.parse import quote

print(getQuotes(quote("NSE:M&MFIN")))

演示:

>>> from googlefinance import getQuotes
>>> from urllib.parse import quote
>>> print(getQuotes(quote("NSE:M&MFIN")))
[{'ID': '11784956', 'StockSymbol': 'M&MFIN', 'Index': 'NSE', 'LastTradePrice': '416.55', 'LastTradeWithCurrency': '&#8377;416.55', 'LastTradeTime': '3:30PM GMT+5:30', 'LastTradeDateTime': '2017-08-18T15:30:00Z', 'LastTradeDateTimeLong': 'Aug 18, 3:30PM GMT+5:30'}]