2017-12-30 69 views
2

아래 request은 당일 콘테스트 ID를 찾습니다. 나는 strdriver.geturl에 전달하려고 시도하기 때문에 각 개별 콘테스트 url으로 가서 각 콘테스트 CSV을 다운로드 할 것입니다. 내가 loop을 써야한다고 생각 하겠지만 webdriver으로 무엇이 될지 확신 할 수 없습니다.Selenium Webdriver로 루프 스루 URL

import time 
from selenium import webdriver 
import requests 
import datetime 

req = requests.get('https://www.draftkings.com/lobby/getlivecontests?sport=NBA') 
data = req.json() 

for ids in data: 
    contest = ids['id'] 

driver = webdriver.Chrome() # Optional argument, if not specified will search path. 
driver.get('https://www.draftkings.com/account/sitelogin/false?returnurl=%2Flobby'); 
time.sleep(2) # Let DK Load! 

search_box = driver.find_element_by_name('username') 
search_box.send_keys('username') 
search_box2 = driver.find_element_by_name('password') 
search_box2.send_keys('password') 
submit_button = driver.find_element_by_xpath('//*[@id="react-mobile-home"]/section/section[2]/div[3]/button/span') 
submit_button.click() 
time.sleep(2) # Let Page Load, If not it will go to Account! 


driver.get('https://www.draftkings.com/contest/exportfullstandingscsv/' + str(contest) + '') 
+0

testNG 프레임 워크 –

+0

에서 dataprovider를 사용할 수 있으므로 URL에이 ID가 반환됩니까? 스포츠 = nba 비트인가요? –

+0

그것은 현재 진행중인 모든 컨테스트 ID를 통과합니다. 그 ID를 가지고 가서 ID를 통해 각 콘테스트에 가서 CSV를 내보낼 수 있습니다. –

답변

2

보십시오 : 당신은 파일의 X의 번호를 다운로드 시간의 X의 번호에 대한 부하의 셀레늄을 보낼 필요가 없습니다

import time 
from selenium import webdriver 
import requests 
import datetime 

req = requests.get('https://www.draftkings.com/lobby/getlivecontests?sport=NBA') 
data = req.json() 



driver = webdriver.Chrome() # Optional argument, if not specified will search path. 
driver.get('https://www.draftkings.com/account/sitelogin/false?returnurl=%2Flobby') 
time.sleep(2) # Let DK Load! 

search_box = driver.find_element_by_name('username') 
search_box.send_keys('Pr0c3ss') 
search_box2 = driver.find_element_by_name('password') 
search_box2.send_keys('generic1!') 
submit_button = driver.find_element_by_xpath('//*[@id="react-mobile-home"]/section/section[2]/div[3]/button/span') 
submit_button.click() 
time.sleep(2) # Let Page Load, If not it will go to Account! 

for ids in data: 
    contest = ids['id'] 
    driver.get('https://www.draftkings.com/contest/exportfullstandingscsv/' + str(contest) + '') 
+0

그것이 작동하는 것처럼 보입니다. 병이 나면 오늘 밤에 그것을 확인해야합니다. 잘 하셨어요! –

+0

정적 수면을 사용하지 마십시오. –

0

이 도움말

for ids in data: 
    contest = ids['id'] 
    driver.get('https://www.draftkings.com/contest/exportfullstandingscsv/' + str(contest) + '') 
+0

좋은 생각이 있지만 –

+2

어떻게됩니까? –

0

은 조금을 분해하는 그것의 시간이 될 수 있습니다.
몇 가지 격리 된 함수를 만듭니다.
0. (선택 사항) url을 대상으로 인증 할 권한을 제공하십시오.
1. 모두 수집해야합니다 id (코드의 첫 번째 부분).
2. 특정 id (코드의 두 번째 부분)에 대한 CSV 내보내기.
3. id의 목록을 반복하고 각각에 대해 funC# 2를 호출하십시오.

드라이버 상태 및 인증 쿠키를 저장하기 위해 각각에 대해 입력 인수로 공유합니다.
잘 작동하고 코드를 명확하고 읽기 쉽도록 만듭니다.

0

방문 페이지의 a 요소로 컨테스트 URL을 설정 한 다음 클릭하면됩니다. 그런 다음 다른 ID로 단계를 반복하십시오.

아래 코드를 참조하십시오. 다음과 같은 순서로

req = requests.get('https://www.draftkings.com/lobby/getlivecontests?sport=NBA') 
data = req.json() 
contests = [] 

for ids in data: 
    contests.append(ids['id']) 

driver = webdriver.Chrome() # Optional argument, if not specified will search path. 
driver.get('https://www.draftkings.com/account/sitelogin/false?returnurl=%2Flobby'); 
time.sleep(2) # Let DK Load! 

search_box = driver.find_element_by_name('username') 
search_box.send_keys('username') 
search_box2 = driver.find_element_by_name('password') 
search_box2.send_keys('password') 
submit_button = driver.find_element_by_xpath('//*[@id="react-mobile-home"]/section/section[2]/div[3]/button/span') 
submit_button.click() 
time.sleep(2) # Let Page Load, If not it will go to Account! 

for id in contests: 
    element = driver.find_element_by_css_selector('a') 
    script1 = "arguments[0].setAttribute('download',arguments[1]);" 
    driver.execute_script(script1, element, str(id) + '.pdf') 
    script2 = "arguments[0].setAttribute('href',arguments[1]);" 
    driver.execute_script(script2, element, 'https://www.draftkings.com/contest/exportfullstandingscsv/' + str(id)) 
    time.sleep(1) 
    element.click() 
    time.sleep(3) 
1

. 요청과 셀렌은 쿠키를 공유 할 수 있습니다. 즉, 셀렌으로 사이트에 로그인하고 로그인 세부 정보를 검색하여 요청이나 다른 응용 프로그램과 공유 할 수 있습니다. 잠시 시간을내어 httpie를 확인하십시오. https://httpie.org/doc#sessions 요청과 같이 수동으로 세션을 제어하는 ​​것으로 보입니다. 에서 셀레늄보기 위해 http://docs.python-requests.org/en/master/user/advanced/?highlight=sessions : 요청에 대한

가 볼

http://selenium-python.readthedocs.io/navigating.html#cookies이 Webdriver 블록을 보면, 당신은 프록시를 추가하고 브라우저 헤드리스를로드하거나 살 수 : 그냥 머리가없는 라인을 주석과은을로드해야합니다 브라우저 라이브, 디버깅이 쉽고, 이해하기 쉬운 동작 및 사이트 api/html 로의 변경을 가능하게합니다.

import time 
from selenium import webdriver 
from selenium.common.exceptions import WebDriverException 
import requests 
import datetime 
import shutil 



LOGIN = 'https://www.draftkings.com/account/sitelogin/false?returnurl=%2Flobby' 
BASE_URL = 'https://www.draftkings.com/contest/exportfullstandingscsv/' 
USER = '' 
PASS = '' 

try: 
    data = requests.get('https://www.draftkings.com/lobby/getlivecontests?sport=NBA').json() 
except BaseException as e: 
    print(e) 
    exit() 


ids = [str(item['id']) for item in data] 

# Webdriver block 
driver = webdriver.Chrome() 
options.add_argument('headless') 
options.add_argument('window-size=800x600') 
# options.add_argument('--proxy-server= IP:PORT') 
# options.add_argument('--user-agent=' + USER_AGENT) 

try: 
    driver.get(URL) 
    driver.implicitly_wait(2) 
except WebDriverException: 
    exit() 

def login(USER, PASS) 
    ''' 
    Login to draftkings. 
    Retrieve authentication/authorization. 

    http://selenium-python.readthedocs.io/waits.html#implicit-waits 
    http://selenium-python.readthedocs.io/api.html#module-selenium.common.exceptions 

    ''' 

    search_box = driver.find_element_by_name('username') 
    search_box.send_keys(USER) 

    search_box2 = driver.find_element_by_name('password') 
    search_box2.send_keys(PASS) 

    submit_button = driver.find_element_by_xpath('//*[@id="react-mobile-home"]/section/section[2]/div[3]/button/span') 
    submit_button.click() 

    driver.implicitly_wait(2) 

    cookies = driver.get_cookies() 
    return cookies 


site_cookies = login(USER, PASS) 

def get_csv_files(id): 
    ''' 
    get each id and download the file. 
    ''' 

    session = rq.session() 

    for cookie in site_cookies: 
     session.cookies.update(cookies) 

    try: 
     _data = session.get(BASE_URL + id) 
     with open(id + '.csv', 'wb') as f: 
      shutil.copyfileobj(data.raw, f) 
    except BaseException: 
     return 


map(get_csv_files, ids)