FabioDavidF
FabioDavidF

Reputation: 33

Sending data from search bar to url

I need to send the raw text from a search bar input to my url, but I am getting query strings and I can't figure out how to convert it into text I can use

This is the html that handles said bar

<form method ='GET' action="/entry/">
    <input class="search" type="text" name='q' placeholder="Search Encyclopedia">
</form>

Upvotes: 0

Views: 577

Answers (1)

JohnAlexINL
JohnAlexINL

Reputation: 626

The Wikipedia page on Query Strings seems like it'd be a useful place to start. Modifying strings in Python is pretty straightforward.

Let's take this example URL including a query: https://example.com/path/to/page?name=ferret&color=purple

If we assume the variable url is going to equal whatever URL we're reading, then you could use the split method to easily break it unto usable pieces.

Variables going to come after the path, and always are preceded by a ?, then a variable=value statement, with & between them to mark additional declarations.

So, we could build a function that breaks apart those requests into seperate values.

variablename = []
variablevalue = []

url = input("URL: ")
query = str ( url.split("?")[1] ) # Everything after the "?", as a string object
requests = query.split("&") # all of the requests, as an array, starting at [0]

for a in range (0, len(requests) ): # For every single variable in the query
    request = str ( requests[a] )
    variablename.append( request.split("=")[0] )
    variablevalue.append( request.split("=")[1] )
    
for a in range(0, len(variablename) ):
    print("%s = %s" % (variablename[a], variablevalue[a] ) )

Using that script, with the example URL I gave, you would get this as an output:

name = ferret
color = purple

I'm not sure what your exact purpose is, but it should be fairly easy to modify the code I've provided to suit your needs. Hope this was helpful!

Upvotes: 1

Related Questions