puzzle
puzzle

Reputation: 25

urllib.parse I am trying to parse a url however it is parsing part of it and not all

here I have a url:

https://www.httpbin.org/get?course=networking&assignment=1

and I want to parse it so that I can do something like this:

remote_ip = socket.gethostbyname(addr)
message = "GET /get?course=networking&assignment=1 HTTP/1.1\nHost: " +remote_ip +"\n\n"

However It is only giving me part of the url and missing the rest. I am storing the url in a variable called address and parsing it as follows:

parsed = urlparse(address)

and I only get this: ParseResult(scheme='https', netloc='www.httpbin.org', path='/get', params='', query='course=networking', fragment='')

Upvotes: 0

Views: 432

Answers (1)

宏杰李
宏杰李

Reputation: 12168

import socket
from urllib.parse import urlparse
url = 'https://www.httpbin.org/get?course=networking&assignment=1'
res = urlparse(url)
remote_ip = socket.gethostbyname(res.netloc)
message = "GET {path}?{query} HTTP/1.1\nHost: {ip}\n\n".format(path=res.path, query=res.query, ip=remote_ip)

out:

'GET /get?course=networking&assignment=1 HTTP/1.1\nHost: 54.175.219.8\n\n'

use . to get info in the ParseResult

ParseResult:

ParseResult(scheme='https', netloc='www.httpbin.org', path='/get', params='', query='course=networking&assignment=1', fragment='')

Upvotes: 1

Related Questions