2017-03-01 5 views
0

私は、Google Newspaperの検索結果のリンクを表示し、それらのリンクを特定のキーワードや文脈やデータのために分析する、より大きいコードを作成しています。私はこのすべてを作業に費やしました。結果のページを反復しようとすると、問題が発生します。私はどのように使用するのかわからないAPIなしでこれを行う方法がわかりません。検索結果の複数のページを繰り返し処理できるだけで、分析結果を適用することができます。結果のページを反復する簡単な解決策があるようですが、私はそれを見ていません。Pythonのページ間の繰り返しGoogle検索

この問題にアプローチする方法はありますか?私はPythonに若干の新しさを感じています。これらすべてのスクレイピングテクニックを自分自身に教えているので、ここで単純なものが欠落しているかどうかはわかりません。私はこれが自動検索を制限するGoogleの問題かもしれないが、最初の100程度のリンクを引っ張っても有益であることは分かっている。私は通常のGoogle検索からこの例を見てきましたが、Googleの新聞検索では見つかりませんでした。

ここにコードの本文があります。あなたが提案をしている行があれば、それは役に立ちます。前もって感謝します!

def get_page_tree(url): 
page = requests.get(url=url, verify=False) 
return html.fromstring(page.text) 

def find_other_news_sources(initial_url): 
    forwarding_identifier = '/url?q=' 
    google_news_search_url = "https://www.google.com/search?hl=en&gl=us&tbm=nws&authuser=0&q=ohio+pay-to-play&oq=ohio+pay-to-play&gs_l=news-cc.3..43j43i53.2737.7014.0.7207.16.6.0.10.10.0.64.327.6.6.0...0.0...1ac.1.NAJRCoza0Ro" 
    google_news_search_tree = get_page_tree(url=google_news_search_url) 
    other_news_sources_links = [a_link.replace(forwarding_identifier, '').split('&')[0] for a_link in google_news_search_tree.xpath('//a//@href') if forwarding_identifier in a_link] 
    return other_news_sources_links 

links = find_other_news_sources("https://www.google.com/search? hl=en&gl=us&tbm=nws&authuser=0&q=ohio+pay-to-play&oq=ohio+pay-to-play&gs_l=news-cc.3..43j43i53.2737.7014.0.7207.16.6.0.10.10.0.64.327.6.6.0...0.0...1ac.1.NAJRCoza0Ro") 

with open('textanalysistest.csv', 'wt') as myfile: 
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) 
    for row in links: 
     print(row) 

答えて

0

私はGoogleの(連続した結果ページの、すなわち束、注目コンテンツの表と各)に類似した構造を持つサイトのパーサを構築するに探しています。

Seleniumパッケージ(ページ要素ベースのサイトナビゲーション用)とBeautifulSoup(html解析用)の組み合わせは、書かれたコンテンツを収穫するための選択肢のようです。あなたはそれが役に立つかもしれませんが、スクラップを抑止するためにGoogleがどんな種類の防御を行っているかはわかりません。

セレン、beautifulsoupとgeckodriverを使用してMozilla Firefox用可能な実装:この後

from bs4 import BeautifulSoup, SoupStrainer 
from bs4.diagnose import diagnose 
from os.path import isfile 
from time import sleep 
import codecs 
from selenium import webdriver 

def first_page(link): 
    """Takes a link, and scrapes the desired tags from the html code""" 
    driver = webdriver.Firefox(executable_path = 'C://example/geckodriver.exe')#Specify the appropriate driver for your browser here 
    counter=1 
    driver.get(link) 
    html = driver.page_source 
    filter_html_table(html) 
    counter +=1 
    return driver, counter 


def nth_page(driver, counter, max_iter): 
    """Takes a driver instance, a counter to keep track of iterations, and max_iter for maximum number of iterations. Looks for a page element matching the current iteration (how you need to program this depends on the html structure of the page you want to scrape), navigates there, and calls mine_page to scrape.""" 
    while counter <= max_iter: 
     pageLink = driver.find_element_by_link_text(str(counter)) #For other strategies to retrieve elements from a page, see the selenium documentation 
     pageLink.click() 
     scrape_page(driver) 
     counter+=1 
    else: 
     print("Done scraping") 
    return 


def scrape_page(driver): 
    """Takes a driver instance, extracts html from the current page, and calls function to extract tags from html of total page""" 
    html = driver.page_source #Get html from page 
    filter_html_table(html) #Call function to extract desired html tags 
    return 


def filter_html_table(html): 
    """Takes a full page of html, filters the desired tags using beautifulsoup, calls function to write to file""" 
    only_td_tags = SoupStrainer("td")#Specify which tags to keep 
    filtered = BeautifulSoup(html, "lxml", parse_only=only_td_tags).prettify() #Specify how to represent content 
    write_to_file(filtered) #Function call to store extracted tags in a local file. 
    return 


def write_to_file(output): 
    """Takes the scraped tags, opens a new file if the file does not exist, or appends to existing file, and writes extracted tags to file.""" 
    fpath = "<path to your output file>" 
    if isfile(fpath): 
     f = codecs.open(fpath, 'a') #using 'codecs' to avoid problems with utf-8 characters in ASCII format. 
     f.write(output) 
     f.close() 
    else: 
     f = codecs.open(fpath, 'w') #using 'codecs' to avoid problems with utf-8 characters in ASCII format. 
     f.write(output) 
     f.close() 
    return 

、それが呼び出すだけの問題である:このスクリプトは、その結果を前提としていること

link = <link to site to scrape> 
driver, n_iter = first_page(link) 
nth_page(driver, n_iter, 1000) # the 1000 lets us scrape 1000 of the result pages 

注意スクラップしようとしているページには順番に番号が付けられ、それらの番号は 'find_element_by_link_text'を使用してスクラップページのhtmlから取り出すことができます。ページから要素を取得する他の方法については、セレン資料hereを参照してください。

また、ブラウザと通信するためには、これが依存するパッケージとセレンが必要なドライバをダウンロードする必要があります(この場合はgeckodriver、geckodriverをダウンロードしてフォルダに入れてから'executable_path'の実行可能ファイルに)

これらのパッケージを使用すると、時間パッケージ(Pythonのネイティブ)を使用してサーバー要求を広め、あなたが掻爬しているサーバー。私は自分自身のプロジェクトのためにそれを必要としませんでしたが、最初の質問に対するhereの2番目の答えを見ると、4番目のコードブロックで使用された時間モジュールの実装例です。

Yeeeeaaaahhh ...上位の担当者が編集してbeautifulsoup、seleniumおよびtimeのドキュメントへのリンクを追加できれば、それは素晴らしいことです。

関連する問題