2017-03-01 7 views
0

나는 Google 신문 검색 결과의 링크를 표시 한 다음 특정 키워드 및 컨텍스트 및 데이터에 대한 해당 링크를 분석하는 큰 코드를 작성 중입니다. 이 모든 것이 작동하도록 모든 것을 얻었습니다. 결과의 페이지를 반복 할 때 문제가 생깁니다. API를 사용하지 않고이 작업을 수행하는 방법을 잘 모르겠습니다. 사용 방법을 모르겠습니다. 검색 결과를 여러 페이지에 걸쳐 반복 할 수 있어야 분석 결과를 적용 할 수 있습니다. 결과 페이지를 반복하는 간단한 해결책이있는 것처럼 보이지만 나는 그것을 보지 않을 것입니다.페이지를 통해 반복하는 파이썬 Google 검색

이 문제에 접근하는 방법에 대한 제안 사항이 있습니까? 나는 다소 파이썬에 익숙하지 않고 이러한 모든 근근이 살아있는 기술을 가르쳐 왔기 때문에 여기에 간단한 것을 놓치고 있는지 확실하지 않습니다. 나는 이것이 자동 검색을 제한하는 Google의 문제 일 수 있지만 첫 번째 링크 만 가져 오면 도움이 될 것임을 알고 있습니다. 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

나는 구글의 유사 구조 (연속 결과 페이지의 즉 무리 관심 내용의 테이블 각)와 사이트에 대한 파서 구축에 찾고 있어요.

Selenium 패키지 (페이지 요소 기반 사이트 탐색 용)와 BeautifulSoup (html 구문 분석 용)의 조합은 작성된 콘텐츠를 수집하기위한 선택의 여지가있는 것처럼 보입니다. 비록 내가 어떤 종류의 방어 Google이 긁어 모으기를 막을 수 있는지 알지 못하지만, 당신도 유용하다는 것을 알게 될 것입니다.

셀레늄, BeautifulSoup로하고 geckodriver 사용하여 모질라 파이어 폭스에 대한 가능한 구현 :이 스크립트는 결과가 있다고 가정

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 

참고 :이 후

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 

은, 그냥 전화의 문제이다 스크래핑하려는 페이지는 순차적으로 번호가 매겨지며 그 번호는 'find_element_by_link_text'를 사용하여 스크랩 한 페이지의 html에서 검색 할 수 있습니다. 페이지에서 요소를 검색하는 다른 전략은 셀렌 문서 here을 참조하십시오.

또한 셀프가 필요로하는 패키지와 셀레늄이 브라우저와 대화하기 위해 다운로드해야합니다 (이 경우 geckodriver, geckodriver를 다운로드하여 폴더에 넣은 다음 'executable_path'의 실행 파일에)

이러한 패키지를 사용하면 결국 시간 패키지 (Python 기본)를 사용하여 서버 요청을 분산시켜 해당 패키지에 허용 된 최대 요청 수를 초과하지 않도록 할 수 있습니다. 당신이 긁고있는 서버. 나는 내 자신의 프로젝트를 위해 그것을 필요로하지 않았지만,, 네 번째 코드 블록에서 사용 된 시간 모듈을 사용한 구현 예에 대한 두 번째 대답을 참조하십시오.

Yeeeeaaaahhh ... 담당자가 더 높은 사람이 beautifulsoup, selenium 및 time 문서에 대한 링크를 편집하고 추가 할 수 있다면 좋을 것입니다.