首页 > 解决方案 > 如何使用 Selenium 在循环中追加

问题描述

def show(request):
    driver = webdriver.Chrome('/Users/colegulledge/desktop/chromedriver')
    driver.get('https://www.horrycounty.org/bookings')

    sleep(random() + 2)
    date_form = driver.find_element_by_id('txtBookingDate')
    ##we are going to loop through the start date-end date in this input box

    def daterange(start_date, end_date):
        for n in range(int((end_date - start_date).days)):
            yield start_date + timedelta(n)

    start_date = date(2020, 1, 1)
    end_date = date(2020, 1, 3)

    def change_date_format(dt):
        return re.sub(r'(\d{4})/(\d{1,2})/(\d{1,2})', '\\2-\\3-\\1', dt)
     ##to change the format to month-day-year

    for single_date in daterange(start_date, end_date):
        days = (single_date.strftime(format("%Y/%m/%d")))
        days = (change_date_format(days))
        date_form.send_keys(days)
        sleep(2)
        ##Changing the date format and using send keys we put in in the inputbox



        for el in days:
            search = driver.find_element_by_css_selector("span.btn-primary")
            driver.execute_script("arguments[0].click();", search)
            sleep(2)

            inmate_info = driver.find_elements_by_class_name("cellLarge")
            rs = []
            for p in range(len(inmate_info)):
                rs.append(inmate_info[p].text.strip())



            date_form.clear()
    print(rs)

            ##the website keeps the previous date in the input box, so we must
            ##clear the input box and repeat the loop

    return HttpResponse(rs)

所以每当我这样做时, rs 只返回最后一天的记录。我相信我的函数没有附加到列表中,而是替换它。这可能是显而易见的,但我是一个缺乏经验的人,正在从事我的第一个重大项目。有什么想法/建议吗?谢谢

标签: pythondjangoseleniumfor-loopnested-loops

解决方案


(移动评论回答)

您正在rs循环中重置,以便清除任何以前的数据。

要收集所有数据,请移至rs = []循环上方:

rs = []
for single_date in daterange(start_date, end_date):
   .......

推荐阅读