0

I am trying to define a google search with the AJAX interface using the very good function described here (A Martelli) Google Search from a Python App

........
query = urllib.urlencode({'q': searchfor}) 
....

If I define the variable searchfor = "big car", the query generated is big+car. However I want to generate the query "big car" (those two words ocurring together).

Q1) That is, I would like to define an explicit phrase in my query (in google I would enter the "phrase" within double quotes).

Q2) How can I define a query where I wxclude a certain term. (In google you enter the "-" sign).

Community
  • 1
  • 1
andreSmol
  • 1,028
  • 2
  • 18
  • 30
  • 1
    Looking at the google URL called, the differences in the query for the words and the string are: `q=big+car` versus `q=%22big+car%22`. So maybe you should try quering the quoted string '"big car"' (single with inner double). When encoded this produces the observed query. Not tested so that I do not write it as an answer. – joaquin Sep 25 '11 at 09:10
  • 1
    for the second question, you should try `searchfor = "big -car"` it also generates the expected query `q=big+-car` – joaquin Sep 25 '11 at 09:18
  • Thanks for the answer that clarifies that I should use the same format as used in the google query UI. It works! I got confused because when I run the function showsome('"big car"'), I got only 183000 hits. When I use google webpage I got 3million hits (id=resultStats>About 3,080,000 results). I guess the function "showsome" is only counting the number of hits in the 4 web pages. How could I get the total count....I am only interssted in the total count..nothing else. – andreSmol Sep 25 '11 at 11:50

1 Answers1

3

1) Put the quotes in searchfor string, searchfor = '"big car"'. You can also define the strings with double quotes and escape the double quote character: searchfor = "\"big car\"". See Googles Python class for information about string literals in Python.

Just to be clear, the + is the urlencoded space character, it will be interpreted as a plain space when Google retrieves it. The urlencoded query with the quotes will be q=%22big+car%22, where %22 is a double quote.

urllib.urlencode will encode the string correctly to be submitted in the URL.

2) Just use the same syntax as you would when you use Google normally. searchfor = '"big car" -hummer'

andreaspelme
  • 3,270
  • 23
  • 12
  • To use Google normally to search for complete phrase I had to add "allintext:" prefix now. Should I add it in Python? – Alex Martian Jul 08 '16 at 05:13