사이트에서 일부 데이터를 가져 오려고하지만 페이지를 변경할 때 데이터를 가져 오는 데 약간의 문제가 있습니다. 내가 처음 페이지로 갈 때 원하는 데이터를 얻었지만 다른 페이지 (아약스 클릭)를 클릭하면 이전 데이터가 계속 나타납니다.python/selenium을 사용할 때 AJAX에서 페이지를 변경 한 후 어떻게 데이터를 가져올 수 있습니까?
나는 이것을하는 방법의 논리가 셀레늄이라는 것을 잘 모르겠다. webdriver를 통해 페이지를 얻은 다음 데이터를 처리합니다. 링크를 클릭하고 webdriver 인스턴스를 다시 프로세스로 보내면 이전 데이터 만 포함됩니다. 예를 들어
:
Page 1
1
2
3
Page 2:
4
5
6
I가 1 페이지를 처리하고 데이터를 얻을 수있다 (1,2,3)하지만 (I 열거되어 볼 수있는) 두 번째 페이지를 클릭 할 때 I는 여전히 1을 얻을 결과 2,3.
이from selenium import webdriver
import os
import time
# Firefox
#driver = webdriver.Firefox()
# Google Chrome
driver = webdriver.Chrome()
driver.get('http://www.theglobeandmail.com/globe-investor/markets/stocks/financials/?q=RY-T&page=incomeStatement&frequency=ANNUAL#financials-content')
def scraper(driver): #get the data out
rawData = driver.find_elements_by_xpath('//*[@id="a-stockFinancials_tabs"]/div[2]/div[2]/div/div[2]/ul/li[2]/div/table/tbody/tr/td')
print rawData[50].get_attribute("innerHTML") #get operating income: 11,081.00 is for year 2013 only, 18,778.00 for 2009,etc..
# for element in rawData:
# print element.get_attribute("innerHTML")
print '*** Done a page ****'
#start
scraper(driver)
#number of tabs:
numberOfentries = driver.find_elements_by_xpath('//*[@id="a-stockFinancials_tabs"]/div[2]/div[2]/div/div[1]')
#get the number of buttons listed there
testList = os.linesep.join([s for s in numberOfentries[0].get_attribute("innerHTML").splitlines() if s])
countButtons = len(testList.splitlines()) -3 #remove 2 because of the forward/backward button count and take 1 more extra because we start on page 1 and if there is 4 pages then we need only need to move forward 3 pages
for clicks in range(0,countButtons):
print clicks
driver.find_element_by_id('a-stockFinancials_link_incomeStatement_ANNUAL_next').click() #driver.find_elements_by_xpath("xpath=//a[contains(@id,'a-stockFinancials_link_incomeStatement_ANNUAL_next')")
time.sleep(1)
scraper(driver)
driver.close()