【问题标题】:Google search from Python program来自 Python 程序的 Google 搜索
【发布时间】:2015-12-20 05:53:03
【问题描述】:

我正在尝试获取一个输入文件,读取每一行,使用该行搜索 google 并打印来自查询的所有搜索结果,前提是结果来自特定网站。一个简单的例子来说明我的观点,如果我搜索狗,我只想从维基百科打印结果,无论是维基百科的一个结果还是十个结果。我的问题是我得到了非常奇怪的结果。下面是我的 Python 代码,其中包含我想要结果的特定 URL。

我的程序

inputFile = open("small.txt", 'r') # Makes File object
outputFile = open("results1.txt", "w") 
dictionary = {}  # Our "hash table"
compare = "www.someurl.com/" # urls will compare against this string

from googlesearch import GoogleSearch

for line in inputFile.read().splitlines():
    lineToRead = line
    dictionary[lineToRead] = [] #initialzed to empty list
    gs = GoogleSearch(lineToRead)
    for url in gs.top_urls():
        print url # check to make sure this is printing URLs
        compare2 = url
        if compare in compare2: #compare the two URLs, if they match 
            dictionary[lineToRead].append(url) #write out query string to dictionary key & append EACH url that matches 
inputFile.close()

for i in dictionary:
    print i # this print is a test that shows what the query was in google (dictionary key)
    outputFile.write(i+"\n")
    for j in dictionary[i]: 
        print j # this print is a test that shows the results from the query which should look like correct URL: "www.medicaldepartmentstore.com/..."(dictionary value(s))
        outputFile.write(j+"\n") #write results for the query string to the output file.

我的输出文件不正确,它应该被格式化的方式是

query string
http://www.
http://www.
http://www.
query string
http://www.
query string
http://www.medical...
http://www.medical...

【问题讨论】:

    标签: python google-search


    【解决方案1】:

    您能否在查询时将结果范围限制在特定站点(例如维基百科)?例如,使用:

    gs = GoogleSearch("site:wikipedia.com %s" % query) #as shown in https://pypi.python.org/pypi/googlesearch/0.7.0
    

    这将指示 Google 仅返回来自该域的结果,因此您无需在看到结果后对其进行过滤。

    【讨论】:

    • 如果您关心来自多个域的结果,您可以编写一个小方法来生成site 字符串。要做多个站点,只需使用OR - 比如site:wikipedia.org OR site:stackoverflow.com
    • 我没有想到,但这正是我想做的。 @Cahit
    • @Tommy,对于不同的问题,这是一个很好的建议,但我希望将我的结果限制在一个特定的域。
    【解决方案2】:

    我认为@Cahit 的想法是正确的。 只是查询字符串行的唯一原因是因为您要查找的域不在top_urls() 中。您可以通过检查给定键的字典中包含的数组是否为空来验证这一点

    for i in dictionary:
        outputFile.write("%s: " % str(i))
        if len(dictionary[i]) == 0:
            outputFile.write("No results in top_urls\n")
        else:
            outputFile.write("%s\n" % ", ".join(dictionary[i]))
    

    【讨论】:

      猜你喜欢
      • 2010-12-12
      • 2017-06-19
      • 2012-06-18
      • 2020-04-06
      • 2014-12-30
      • 1970-01-01
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多