2017-08-26 97 views
0

我有一個相對較大的項目,其中搜索Google已返回缺失值的最佳結果。在Python中使用谷歌搜索可以得到我需要的確切結果。當試圖使用自定義搜索爲了解除我的查詢限制時,返回的結果不是遠程接近我需要的。我有以下代碼(在Searching in Google with Python建議)返回正是我需要的,這是完全一樣的事情,當我在谷歌的網站上搜索,但被阻止,由於過多的http請求......將Google自定義搜索配置爲像google.search一樣工作()

from google import search 

def google_scrape(url): 
    cj = http.cookiejar.CookieJar() 
    opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) 
    thepage = opener.open(url) 
    soup = BeautifulSoup(thepage, "html.parser") 
    return soup.title.text 

i = 1 
# queries = ['For. Policy Econ.','Int. J. Soc. For.','BMC Int Health Hum. Rights', 
#   'Environ. Health Persp','Environ. Entomol.','Sociol. Rural.','Ecol. Soc.'] 

search_results = []  
abbrevs_searched = [] 
url_results = [] 

error_names = [] 
error = [] 

#Note, names_to_search is simply a longer version of the commented our queries list. 
for abbreviation in names_to_search: 
    query = abbreviation 
    for url in search(query, num=2,stop=1): 
     try: 
      a = google_scrape(url) 
      print(str(i) + ". " + a) 
      search_results.append(a) 
      abbrevs_searched.append(query) 
      url_results.append(url) 
      print(url) 
      print(" ") 
     except Exception as e: 
      error_names.append(query) 
      error.append(query) 
      print("\n\n***************"," Exeption: ",e) 
     i += 1 

而且我在下面的方式我的谷歌自定義搜索引擎代碼設置...

import urllib 
from bs4 import BeautifulSoup 
import http.cookiejar 
from apiclient.discovery import build 
"""List of names to search on google""" 
names_to_search = set(search_list_1+search_list) 
service = build('customsearch', 'v1',developerKey="AIz**********************") 
rse = service.cse().list(q="For. Policy Econ.",cx='*******************').execute() 
rse 

我的谷歌自定義搜索引擎設置都設置爲搜索Google.com。截至目前,所有其他設置都是默認的,除了網站是Google.com之外。

+0

你使用哪種谷歌搜索API? – ands

+0

我在第一個示例中使用了Google的Python包中的搜索,該示例的工作方式如下,並且我在第二個示例中通過我的個人應用程序使用了自定義搜索引擎,該搜索引擎沒有返回我想要的內容。我更新了導入以正確反映每個給定的代碼塊。 – Min

+0

你會得到哪個錯誤? – ands

回答

0

據我可以告訴python模塊的問題不是在python模塊中的限制,但谷歌不允許用腳本刮頁面的事實。當我運行你的程序(與谷歌模塊)我得到HTTP Error 503。這是因爲在短時間內有太多請求後,Google會要求您輸入驗證碼,並且沒有可以繞過驗證碼的模塊。所以其他選項使用Google Custom Search API。與此相關的問題是它的目的是搜索你的網頁。

谷歌自定義搜索使您能夠爲您的網站,您的博客或一組網站創建搜索引擎。 Read more

有一種方法如何搜索整個網絡如同解釋Bangkokiananswer

要創建一個谷歌自定義搜索引擎,其搜索整個網站:

  1. Google Custom Search homepage,點擊創建一個自定義搜索引擎。
  2. 輸入您的搜索引擎的名稱和說明。
  3. 下定義搜索引擎,在網站搜索框中,輸入至少一個有效的URL(現在,只要把www.anyurl.com讓過去 此屏幕。更多關於這個版本)。
  4. 選擇您需要的CSE版並接受服務條款,然後單擊下一步。選擇所需的佈局選項,然後單擊 接下來。
  5. 單擊「下一步」部分下的任意鏈接以導航到您的控制面板。
  6. 在左側的菜單,控制面板中,單擊基礎知識。
  7. 在搜索首選項部分,選擇搜索整個網絡,但強調包含的網站。
  8. 單擊保存更改。
  9. 在左側菜單的「控制面板」下,單擊「站點」。
  10. 刪除您在初始設置過程中輸入的網站。

您已經創建了一個自定義搜索引擎等等Google Custom Search您需要在搜索引擎點擊你已經有(它可能會成爲「谷歌」,標有圖片波紋管的紅色框): enter image description here 現在您需要在搜索首選項部分選擇搜索整個網頁,但強調包含網站(步驟7),然後單擊添加按鈕: enter image description here 鍵入http://www.example.org/,將其設置爲僅包含特定頁面,然後單擊保存: enter image description here 之後,選擇你的舊websit e和單擊刪除: enter image description here 更新保存更改: enter image description here 不幸的是,這不會提供相同的rusult作爲serching網站:

注意,結果可能不匹配的結果,你會通過在Google Web搜索上搜索獲得。 Read more

此外,您可以只使用免費版本:

本文僅適用於免費的基本自定義搜索引擎。您無法將Google網站搜索設置爲搜索整個網絡。 Read more

而且有每天100所搜索查詢的限制:

對於CSE的用戶,該API提供每天100個搜索查詢是免費的。 Read more

唯一的其他選擇是使用API​​來自其他搜索引擎。似乎只有一個免費的是FAROO API

編輯: 您可以在python中使用selenium webdriver來模仿瀏覽器的使用。有options使用Firefox,Chrome,Edge或Safari webdrivers(它實際上打開Chrome並執行搜索),但這很煩人,因爲您實際上並不想看到瀏覽器。但有這個解決方案,你可以使用PhantomJS

PhantomJS是一款帶JavaScript API的無頭WebKit腳本。

here下載。提取並看看如何使用它例如在下面(我寫了簡單的類,你可以使用,你只需要改變的路徑,PhantomJS):

import time 
from urllib.parse import quote_plus 
from selenium import webdriver 


class Browser: 

    def __init__(self, path, initiate=True, implicit_wait_time = 10, explicit_wait_time = 2): 
     self.path = path 
     self.implicit_wait_time = implicit_wait_time # http://www.aptuz.com/blog/selenium-implicit-vs-explicit-waits/ 
     self.explicit_wait_time = explicit_wait_time # http://www.aptuz.com/blog/selenium-implicit-vs-explicit-waits/ 
     if initiate: 
      self.start() 
     return 

    def start(self): 
     self.driver = webdriver.PhantomJS(path) 
     self.driver.implicitly_wait(self.implicit_wait_time) 
     return 

    def end(self): 
     self.driver.quit() 
     return 

    def go_to_url(self, url, wait_time = None): 
     if wait_time is None: 
      wait_time = self.explicit_wait_time 
     self.driver.get(url) 
     print('[*] Fetching results from: {}'.format(url)) 
     time.sleep(wait_time) 
     return 

    def get_search_url(self, query, page_num=0, per_page=10, lang='en'): 
     query = quote_plus(query) 
     url = 'https://www.google.hr/search?q={}&num={}&start={}&nl={}'.format(query, per_page, page_num*per_page, lang) 
     return url 

    def scrape(self): 
     #xpath migth change in future 
     links = self.driver.find_elements_by_xpath("//h3[@class='r']/a[@href]") # searches for all links insede h3 tags with class "r" 
     results = [] 
     for link in links: 
      d = {'url': link.get_attribute('href'), 
       'title': link.text} 
      results.append(d) 
     return results 

    def search(self, query, page_num=0, per_page=10, lang='en', wait_time = None): 
     if wait_time is None: 
      wait_time = self.explicit_wait_time 
     url = self.get_search_url(query, page_num, per_page, lang) 
     self.go_to_url(url, wait_time) 
     results = self.scrape() 
     return results 




path = '<YOUR PATH TO PHANTOMJS>/phantomjs-2.1.1-windows/bin/phantomjs.exe' ## SET YOU PATH TO phantomjs 
br = Browser(path) 
results = br.search('For. Policy Econ.') 
for r in results: 
    print(r) 

br.end() 
相關問題