2017-03-16 89 views
0

我試圖創建一個循環,每次使用增量日期鏈接打開一個新的Chrome選項卡 - 例如:www.biguser.com/31-04-2015,然後打開www.biguser。 com/01-05-2015 打開鏈接後,它會點擊一個具有標準.csv格式的可下載鏈接(使用Selenium)。因此,我搜索與'csv'find_element _by_partial_link_text的鏈接,然後單擊鏈接。在Python中循環增量日期

下面的代碼 -

from datetime import timedelta, date 
import selenium.webdriver as webdriver 
import selenium.webdriver.support.ui as ui 
import time 
import urllib2 
import re 
from BeautifulSoup import BeautifulSoup 
from selenium.webdriver.common.keys import Keys 

link_1 = "https://www.biguser.com/date=" #this is part 1 (prefix) of the link 
link_2 = "&section=q" #this part comes after date is put in dd-mm-yyyy format 

driver=webdriver.Chrome() 
#loop for determining the increments in date 
def daterange(start_date, end_date): 
    for n in range(int ((end_date - start_date).days)): 
     yield start_date + timedelta(n) 

start_date = date(2013, 12, 31) #defining my start date 
end_date = date(2015, 12, 31) #defining my end date 

while True: 
#loop begins 
     for single_date in daterange(start_date, end_date): 
      driver.get(link_1+single_date.strftime("%d-%m-%Y")+link_2) #opens the concatenated link 
      driver.find_element_by_partial_link_text('csv').click() #finds 'csv' text and clicks on the link that contains it 
      time.sleep(5) #waits for 5 seconds for everything to settle down 
      driver.get("chrome://newtab/") #opens a new Chrome tab 

,這裏是我與它的問題 下載的文件僅適用於平日裏,這意味着還有就是對網頁,而不只是一個錯誤信息上沒有「CSV」即「沒有找到指定日期的文件,請嘗試其他日期。」只要代碼遇到這種情況,它就會退出程序。

我希望代碼在鏈接不可用的情況下直接跳過「點擊鏈接」事件並繼續下一個日期。該頁面沒有href或標籤。

PS:作爲一個極端的初學者,我已經把這個代碼通過各種實驗(你可以看到我已經加載了太多的庫太;))

回答

0

Date類具有一個工作日()方法,你可以用於檢查給定的日期是否是工作日。我會建議做一個小助手功能的if語句:

def is_weekday(date_object): 
    # days 1-5 are weekdays, 6 and 7 are weekends 
    return date.weekday(date_object) in range(1,6) 

然後,你可以檢查:

if is_weekday(<your date here>): 
    ...make the link... 

如果有其他的因素,如假期,你可能不能夠預測到所有這些,所以我會建議圍繞行動失敗的嘗試/除了塊:

for single_date in daterange(start_date, end_date): 
    try: 
    driver.get(link_1+single_date.strftime("%d-%m-%Y")+link_2) #opens the concatenated link 
    driver.find_element_by_partial_link_text('csv').click() #finds 'csv' text and clicks on the link that contains it 
    time.sleep(5) #waits for 5 seconds for everything to settle down 
    driver.get("chrome://newtab/") #opens a new Chrome tab 
    except: 
    continue #this will return to the top of the loop and move on to the next link 
+0

我可以嘗試,但這並不能解決問題,因爲有一週內的其他假期。我需要循環才能進入下一個鏈接,以防無法找到可點擊的鏈接。據我瞭解,這是我的邏輯。 –