Python在同一行上进行多次迭代

如何解决Python在同一行上进行多次迭代

我想遍历sqlite表中的行,并且代码正在工作,但是它在移至下一行之前运行了4次该功能

def get_ship_tm_window():
    # connect to database
    conn = sqlite3.connect('PSC.sdb')
    # create cursor
    c = conn.cursor()
    f = conn.cursor()
    c.execute("DELETE FROM 'inspections tm'")
    conn.commit()
    with requests.Session() as s:
        for row in c.execute("SELECT * FROM ships ORDER BY ISM"):
            print(row)
            ship_imo = row[1]
            print(ship_imo)
            get_tm_windows_access(s,ship_imo)
            f.execute(
                "INSERT INTO 'inspections tm' VALUES(:name,:imoship,:lastinsp,:ship_risk,:date_pii,:date_pi,:prio)",{
                    'name': row[0],'imoship': row[1],'lastinsp': '','ship_risk': get_tm_windows_access(s,ship_imo)[0],'date_pii': get_tm_windows_access(s,ship_imo)[2],'date_pi': get_tm_windows_access(s,ship_imo)[3],'prio': get_tm_windows_access(s,ship_imo)[1]
                })
            conn.commit()
    conn.close()


get_ship_tm_window()

结果是:

('HANNA OLDENDORFF',9731614,'Anglo-Eastern (Germany) GmbH',5365996,'High','High') # prints row OK
9731614 #prints imo OK
7B9E9C8F-EAF8-46FA-A09E-6B852A5C7F4C #1ST TIME
High Risk Ship #1ST TIME
Priority I #1ST TIME
05/09/2019 #1ST TIME
05/11/2019 #1ST TIME
7B9E9C8F-EAF8-46FA-A09E-6B852A5C7F4C #2nd time
High Risk Ship #2nd time
Priority I #2nd time
05/09/2019 #2nd time
05/11/2019 #2nd time
7B9E9C8F-EAF8-46FA-A09E-6B852A5C7F4C #3RD TIME
High Risk Ship #3RD TIME
Priority I #3RD TIME
05/09/2019 #3RD TIME
05/11/2019 #3RD TIME
7B9E9C8F-EAF8-46FA-A09E-6B852A5C7F4C #4th time
High Risk Ship #4th time
Priority I #4th time
05/09/2019 #4th time
05/11/2019 #4th time

这里应该停止,但是我又得到了3次,直到它打印出新行。第4次之后,它将移至下一行。

已编辑。

def get_tm_windows_access(s,ship_imo):
    date_from = datetime.Now() - relativedelta(months=36)
    date_to = datetime.Now()

    header = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/68.0.','Cookies': 'PHPSESSID=xxxxxxxxxxxxxxxxxxxxxxxxxxxx'}
    s.headers.update(header)
    r = s.get('https://apcis.tmou.org/public/')
    str_number = re.findall("<span[^>]+(.*?)</span>",r.text)[0]
    numbers = re.findall('[0-9]+',str_number)
    captcha = int(numbers[0]) + int(numbers[1])
    payload = {'captcha': captcha}
    r = s.post('https://apcis.tmou.org/public/?action=login',data=payload)
    check_text = re.findall('<b>(.*?)</b>',r.text)[0]
    payload1 = {'Param': 0,'Value': ship_imo,'imo': ship_imo,'callsign': '','name': '','compimo': '','compname': '','From': date_from.strftime('%d.%m.%Y'),'Till': date_to.strftime('%d.%m.%Y'),'authority': 0,'flag': 0,'class': 0,'ro': 0,'type': 0,'result': 0,'insptype': -1,'sort1': 0,'sort2': 'DESC','sort3': 0,'sort4': 'DESC'
                }
    r = s.post('https://apcis.tmou.org/public/?action=getships',data=payload1)
    try:
        acces_code = re.findall('<input type="hidden" value="([^>]*)"/>',r.text)[0]
        print(acces_code)
        payload2 = {'HUID': acces_code}
        r = s.post('https://apcis.tmou.org/public/?action=getship',data=payload2)
        try:
            ship_risk = re.findall('<h2>(.*?),(.*?)</h2>',r.text)[0][0]
            ship_prio = re.findall('<h2>(.*?),r.text)[0][1]
            ship_window_raw = re.findall('<h2 class="winInsprange">Window inspection Range:\n\n(.*?)</h2>',r.text)[0]
            ship_window_numbers = re.findall('[0-9]+',ship_window_raw)
            pII = ship_window_numbers[0] + '/' + ship_window_numbers[1] + '/' + ship_window_numbers[2]
            pI = ship_window_numbers[3] + '/' + ship_window_numbers[4] + '/' + ship_window_numbers[5]
            return ship_risk,ship_prio,pII,pI
        except IndexError:
            ship_risk = re.findall('<h2>(.*?),r.text)[0][1]
            pII = ''
            pI = ''
            return ship_risk,pI
    except IndexError:
        return '','',''

这里有剩下的代码。 它运行4次对我来说很奇怪。

解决方法

通过将结果分配给命名变量,然后为该元组索引以获取查询参数,避免多次调用其他函数get_tm_windows_access()。当前,您没有将第一个调用分配给任何对象,因此它与显示的行一起显示,但返回的输出未保存在任何地方。只需将输出保存到变量即可。

def get_ship_tm_window():
    # connect to database
    conn = sqlite3.connect('PSC.sdb')

    # create cursor
    c = conn.cursor()
    f = conn.cursor()
    c.execute("DELETE FROM 'inspections tm'")
    conn.commit()

    with requests.Session() as s:
        for row in c.execute("SELECT * FROM ships ORDER BY ISM"):
            print(row)
            ship_imo = row[1]
            print(ship_imo)

            access_data = get_tm_windows_access(s,ship_imo)   # ADJUSTED LINE
            f.execute(
                "INSERT INTO 'inspections tm' VALUES(:name,:imoship,:lastinsp,:ship_risk,:date_pii,:date_pi,:prio)",{
                    'name': row[0],'imoship': row[1],'lastinsp': '','ship_risk': access_data[0],# ADJUSTED LINE
                    'date_pii': access_data[2],# ADJUSTED LINE
                    'date_pi': access_data[3],# ADJUSTED LINE
                    'prio': access_data[1]                     # ADJUSTED LINE
                })
            conn.commit()
    conn.close()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?