Python : Python을 사용하여 동적 웹에서 일일 데이터를 어떻게 스크랩합니까?

Aug 22 2020

다음 코드는 작동하지만 2 월 29 일 이후에 중지됩니다. 웹 사이트는 "잘못된 날짜를 입력했습니다. 검색을 다시 입력하십시오"를 반환하고 "확인"을 클릭해야합니다. 이 문제를 어떻게 해결합니까?

country_search("United States")
time.sleep(2)
date_select = Select(driver.find_element_by_name("dr")) 
date_select.select_by_visible_text("Enter date range...") #All Dates
select_economic_news()
#btnModifySearch
for month in range(1,9):
for day in range(1,32):
    try:
    
        set_from_month(month)
        set_from_date(day)
        set_from_year("2020")
        set_to_month(month)
        set_to_date(day)
        set_to_year("2020")
                
        time.sleep(5)
        #select_economic_news()
        time.sleep(5)
        search_now()
        time.sleep(8)                
                
        export_csv()
        modify_search()
        
        time.sleep(5)        
        #country_remove()
    except ElementClickInterceptedException:
        break

로그 아웃()

답변

derringa Aug 22 2020 at 21:07

초기 게시물에 소개 된 방법 만 사용할 수 있다면 다음과 같이 시도해 보겠습니다.

set_from_year('2020')
set_to_year('2020')
for month in range(1, 9):
    # 1 to 9 for Jan to Aug
    month_str = '0' + str(month)
    set_from_month(month_str)
    set_to_month(month_str)
    for day in range(1, 32):
        # Assuming an error is thrown for invalid days
        try:
            # Store data as needed
        except Exception as e:
            # print(e) to learn from error if needed
            pass

이 메서드를 직접 작성하고 HTML을 반복하고 일일 데이터에 대한 패턴을 찾아야한다는 것이 밝혀지면 여기에 더 많은 내용이 포함됩니다.

ro_ot Aug 22 2020 at 21:22

나는 당신이 한 달의 일수를 동적으로 얻고 싶다고 생각한다. 그래서 당신은 각 날짜에 대한 데이터를 얻기 위해 그 숫자를 반복 할 수있다. 다음과 같이 할 수 있습니다.

from datetime import datetime
currentDay = datetime.today()
# You can set the currentDay using this if you want the data till the current date or 
# whenever your scheduler runs the job.


# Now you need to get the number of days in each month from the chosen date, you can 
# have the corresponding function like getStartMonth() in your program which will 
# return the starting month.  
from calendar import monthrange
daysPerMonth = {}
year = currentDay.year #TODO : change this to getStartYear()
startMonth = 3 # TODO : Implement getStartMonth() in your code.
for month in range(startMonth, currentDay.month+1):
    # monthrange returns (weekday,number of days in that month)
    daysPerMonth[month] = monthrange(year, month)[1]

for month in daysPerMonth.items(): 
    print(month[0], '-',month[1])

다음과 같이 출력됩니다 ( -2020 년 3 월부터 2020 년 8 월까지 한 달의 일수 ).

3 - 31
4 - 30
5 - 31
6 - 30
7 - 31
8 - 31

그런 다음 얻은 dict에서 범위를 참조하면서 일 수 동안 루프를 실행할 수 있습니다. 참고 : 각 날짜에 대한 데이터를 얻기 위해 루프를 실행하는 함수에서 해당 연도의 마지막 날인지 확인하는 조건을 추가하고 그에 따라 연도를 수정하십시오.

M.Liver Aug 23 2020 at 04:57

아마도이 함수를 사용하여 월의 일수를 계산할 수 있습니다.

import datetime


def get_month_days_count(year: int, month: int) -> int:
    date = datetime.datetime(year, month, 1)
    while (date + datetime.timedelta(days=1)).month == month:
        date = date + datetime.timedelta(days=1)
    return date.day