2

I am creating a script to help with some data aggregation. I am trying to test this before I add the rest of the search terms into my list. If I run the script, it displays the search term exactly how I want it on the screen with the print command (It contains +'s in the string), however, when it goes to the browser, it is missing the +'s, it just passes through with the terms and spaces in between. Running the code shows the difference from on screen and chrome browser. Can anyone help me figure out why? Thank you!!

I have tried using "+" + but it still will not go to the browser

import webbrowser

input = input("Enter item> ")
searchterms =["price + availability + made in + year created + "]
price = searchterms[0] + input

print (price)
webbrowser.open_new_tab('http://www.google.com/search?btnG=1&q=%s' %  price)

I expected the output in chrome to have the terms and variable to be separated with + example, if you enter the item "Hammer" on screen it displays price + availability + made in + year created + hammer but in the browser it displays price availability made in year created hammer

MCgendraft
  • 21
  • 2

2 Answers2

2

The + is often used to represent a space in URLs, and I think that includes Google. If you want a literal +, you can use %2B instead. (2B is the hexadecimal ASCII code for +.)

gilch
  • 10,813
  • 1
  • 23
  • 28
0

URL Encoding is a lot easier to search for once you know that's what it's called. See How to urlencode a querystring in Python? for how to do this in Python.

In your specific case this would work:

#!/usr/bin/env python

import urllib.parse
import webbrowser

item = input("Enter item> ") # Rename the variable not to shadow `input()`
searchterms = "price + availability + made in + year created + " # No need for an array
search_query = urllib.parse.quote_plus(searchterms + item) # quote_plus() turns spaces into plus

print("Searching for '%s'..." % search_query)
webbrowser.open_new_tab('http://www.google.com/search?btnG=1&q=%s' % search_query)

See also: https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote_plus

johnsyweb
  • 136,902
  • 23
  • 188
  • 247