Insane Miner
Insane Miner

Reputation: 140

How to get data from a URL with Python

How do I get data from a URL?

URL:

http:\\localhost\?id=1&q=W&random_id=12002H#@&&up=down

Then I want to store it in a dictionary:

data = {
    "id": "1",
    "q": "W",
    "random_id": "12022H#@&",
    "up": "down"
}

Upvotes: 0

Views: 526

Answers (1)

pyOliv
pyOliv

Reputation: 1303

As mentioned in my comment, the given URL does not look valid. I've used the valid encoded one : http:\\localhost\?id=1&q=W&random_id=12002H%23%40%26&up=down. Then you can parse it using urllib:

from urllib import parse
url = 'http:\\localhost\?id=1&q=W&random_id=12002H%23%40%26&up=down'

query = parse.urlsplit(url).query
print(query)
print(parse.parse_qsl(query))
data = dict(parse.parse_qsl(query))
print(data)

Output:

id=1&q=W&random_id=12002H%23%40%26&up=down
[('id', '1'), ('q', 'W'), ('random_id', '12002H#@&'), ('up', 'down')]
{'id': '1', 'q': 'W', 'random_id': '12002H#@&', 'up': 'down'}

Upvotes: 1

Related Questions