2015-01-23 2 views
2

페이지에서 데이터를 추출하기 위해 urllib2로 페이지를 읽으려고합니다. 페이지의 일부는로드 당 생성되며 urllib2로 url을 읽을 때이 부분은 html에 없습니다.python urllib2 - 모든 스크립트가 실행 된 후 페이지 읽기

URL은 http://nametrends.net/name.php?name=Ruby이고 그래프 용으로 생성 된 테이블을 얻으려고합니다. 예를 들어 :

import urllib2 
from bs4 import BeautifulSoup 
req = urllib2.Request('http://nametrends.net/name.php?name=Ruby') 
response = urllib2.urlopen(req) 
the_page = response.read() 

html = BeautifulSoup(the_page) 
print "tabular" in html 
for table in html.find_all('table'): 
    print 1 

는 해당 테이블을 찾을 수없는, 그리고 사업부의 레이블 텍스트 표와 HTML에는 사업부가 (이 없습니다 :

<div aria-label="A tabular representation of the data in the chart." style="position: absolute; left: -10000px; top: auto; width: 1px; height: 1px; overflow: hidden;"> 
     <table> 
      <tbody> 
      <tr><td>Sat Feb 01 1947 00:00:00 GMT-0500 (EST)</td><td>0.048</td><td>0</td></tr> 
      </tbody> 
     </table> 
</div> 

내 현재 코드입니다 테이블을 포함)

답변

3

표는 getfrequencyjson.php 엔드 포인트에 대한 추가 XHR 요청에 의해 리턴 된 데이터로 채워집니다. 실제 브라우저 시뮬레이션,

import requests 

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36'} 

with requests.Session() as session: 
    session.headers = headers 
    session.get('http://nametrends.net/name.php', params={'name': 'ruby'}, headers=headers) 

    response = session.get('http://nametrends.net/chartdata/getfrequencyjson.php', params={'name': 'ruby'}) 
    results = response.json() 
    print results 
+0

우리가 꽤 같은 질문에 답하고있는 것처럼 보입니다.) – Anzel

+0

@Anzel 그래, 우리 스케줄을 조정할 필요가있어. :) – alecxe

+0

이것은 오버 헤드가 적어 보이지만 데이터가 이상한 형식으로 제공됩니다 :) – Quantico

2

대안 다른 보다 urllib2를이 가능하면,이 쉽게 작업의 종류를 수행 할 수 있습니다 셀레늄 : 당신은 당신의 코드에서 해당 요청을하고 JSON 데이터를 분석 할 필요가

시작시
from selenium import webdriver 
from bs4 import BeautifulSoup 

url = 'http://nametrends.net/name.php?name=Ruby' 
driver = webdriver.Firefox() 
driver.get(url) 
# wait until 'tabular' appears on browser 
assert 'tabular' not in driver.page_source 

html = BeautifulSoup(driver.page_source) 
for table in html.find_all('table'): 
    print table 
+0

나는 그것을 시도하고, – Quantico

+0

가 작동한다고보고 할 것이다. 나는 오버 헤드가 적기 때문에 다른 대답을 골랐다. – Quantico

+1

@Quantico, 확실히 그것에 만족합니다. 그리고 네 대답은 매우 견고하며 그 이유에 대해 배울 수 있습니다 ** 그 이유는 요소가 페이지의 첫 부분에 있지 않습니다. HTML이 어떻게 작동하는지 철저히 이해하면 미래에 도움이 될 것입니다. – Anzel

0

나는 갈 것 :

bs = BeautifulSoup(the_page) 
html = bs.html 

귀하의 코드 D를 나쁜 것을 보지 마라. going ...

print str(BeautifulSoup(the_page)) 

아름다운 수프가 페이지를 구문 분석 한 것을 보여줍니다.

+0

beautifulSoup의 문제점은 스크립트에서 생성 된 데이터에 대한 액세스 권한이 없다는 것입니다 – Quantico