NORXND
NORXND

Reputation: 103

Changing url in requests (Python)

I got some strange error with requests. Code is:

    key = key.replace(" ", "_")
    print(key)
    url = f"https://pl.wikipedia.org/api/rest_v1/page/summary/{key}"
    print(url)
    summary = http.get(url)
    summary = summary.json()
    print(summary)

The output from prints:

A

https://pl.wikipedia.org/api/rest_v1/page/summary/A


{'type': 'https://mediawiki.org/wiki/HyperSwitch/errors/bad_request', 'method': 'get', 'detail': 'title-invalid-characters', 'uri': '/pl.wikipedia.org/v1/page/summary/A%0A'}

The site returns an error with uri that is different from the url variable. Why? Anyway, I cannot access it. And I see A is changing to A%0A.

Upvotes: 2

Views: 1441

Answers (1)

NavaneethaKrishnan
NavaneethaKrishnan

Reputation: 1318

Can you see an empty line in the output (2nd line) after the A. That is the problem. A line feed is there at the end of A.. (A\n). You have to remove the \n.

Use key.strip(). This will remove all leading and trailing whitespace.

And URL encoding for LF - line feed (\n) is %0A. That's why your URL changed to A + %0A.

Upvotes: 4

Related Questions