Python:如何使用Python从动态网络抓取每日数据?

时间:2020-08-22 19:55:30

标签: python web-scraping

以下代码有效,但是在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

注销()

3 个答案:

答案 0 :(得分:0)

如果您只能使用初始文章中介绍的方法,那么我会尝试以下方法:

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并找到每日数据的模式,那么还有很多其他事情。

答案 1 :(得分:0)

我相信您希望动态获取一个月中的天数,以便可以循环使用该天数以获取每个日期的数据。您可以按照以下步骤进行操作:

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

然后您可以运行一个天数循环,同时从您获得的字典中引用范围。 注意:在运行循环以获取每个日期数据的函数中,添加一个if条件以检查它是否是一年中的最后一天,并相应地修改年份。

答案 2 :(得分:0)

也许您可以使用以下功能来获取每月的天数:

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