这里我有一个网址:
https://www.httpbin.org/get?course=networking&assignment=1
我想解析它,以便我可以做这样的事情:
remote_ip = socket.gethostbyname(addr)
message = "GET /get?course=networking&assignment=1 HTTP/1.1\nHost: " +remote_ip +"\n\n"
然而,这只是给了我一部分网址而遗漏了剩下的部分。 我将url存储在名为address的变量中,并按如下方式对其进行解析:
parsed = urlparse(address)
我只能得到这个:
ParseResult(scheme='https', netloc='www.httpbin.org', path='/get', params='', query='course=networking', fragment='')
答案 0 :(得分:1)
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)
出:
'GET /get?course=networking&assignment=1 HTTP/1.1\nHost: 54.175.219.8\n\n'
使用.
获取ParseResult
ParseResult:
ParseResult(scheme='https', netloc='www.httpbin.org', path='/get', params='', query='course=networking&assignment=1', fragment='')