【问题标题】:Trouble using webbrowser module to open a Google search使用网络浏览器模块打开 Google 搜索时遇到问题
【发布时间】:2014-09-18 14:17:47
【问题描述】:

嘿,我目前正在尝试使用 python 脚本进行简单的 google 搜索,我在附加视频中逐行关注this person's 代码。问题是我的代码将打开一个新标签并将我带到谷歌主页,但不执行实际搜索。奇怪的是,搜索查询出现在 URL 中,但它并没有做太多其他事情来确认我的搜索。任何帮助将不胜感激,谢谢。

Python 脚本代码

import webbrowser 
new = 2 
tabUrl = "http://google.com/?#q=";
term = raw_input("Enter search query: ");
webbrowser.open(tabUrl+term,new=new);

【问题讨论】:

  • 嘿,对不起,我是这个网站的新手,我是编程新手,我把代码放在原始问题中
  • 其实在我的机器上是可以的。请检查你的网络连接是否有问题。

标签: python google-search


【解决方案1】:
import webbrowser

base_url =
"http://www.google.com/search?q="

query = input("Please enter your search query: ")

webbrowser.open_new(base_url+query)

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
  • 这与现有答案没有什么不同。
  • 我尝试的现有答案不会在 Google 上搜索输入内容,而是将其放在搜索栏上。
【解决方案2】:

试试这个简单的代码:

import webbrowser
base_url = "http://www.google.com/?#q="
query = input("Please enter your search query: ")
final_url = base_url + query.replace(" ","%20")
webbrowser.open_new(final_url)

【讨论】:

    【解决方案3】:

    所以问题来了:当您输入一个单词作为查询字符串(例如“python”)时,您的代码就可以正常工作。但是,如果你想搜索多个单词(“python webbrowser module”),你就有问题了。由于搜索词中有空格,所以 URL 中也会有空格。一些浏览器和操作系统,比如 Ubuntu 14.04 上的 Firefox 28(我当前的设置)可以很好地处理这些空间。但是,其他人可能不会。考虑使用 urllib.quote() 函数将任何违规字符(如空格、逗号、撇号等)更改为它们的 URL 转义对应字符,如用于空格的 %20

    from urllib import quote
    import webbrowser
    
    new = 2 # not really necessary, may be default on most modern browsers
    base_url = "http://www.google.com/?#q="
    query = raw_input("Please enter your search query: ")
    final_url = base_url + quote(query)
    webbrowser.open(final_url, new=new)
    

    【讨论】:

      【解决方案4】:

      试试

      tabUrl = "http://google.com/?q="
      

      没有#。 Technically 在这个哈希符号之后不应该有命名参数。

      【讨论】:

      • 但是,如果您使用 Google,您会发现他们正是这样做的。
      • 嘿,我刚刚尝试使用 tabUrl = "google.com/?q=" 但它只将查询放在搜索中,但没有完成搜索
      • 我还建议使用 @MattDMo 的修复程序。
      猜你喜欢
      • 1970-01-01
      • 2012-01-16
      • 1970-01-01
      • 2013-02-06
      • 2011-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      相关资源
      最近更新 更多