for循环执行

2024-10-01 13:26:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个循环。外部循环从一个文本文件读取,然后进入另一个for循环,当出现异常时,该循环从另一个文本文件读取。内部循环应该退出循环,然后迭代到外部循环中的下一个元素,但是再次迭代后,它应该从内部循环中停止的位置继续。你知道吗

你知道用python怎么做吗?你知道吗

代码如下:

with open('E:\marr.txt') as f:
    content = f.readlines()
content = [x.strip() for x in content]
with open('E:\prlist.txt') as f:
    content1 = f.readlines()
content1 = [x.strip() for x in content1]
with open('E:\Master\master1.csv', 'a') as f:
    headers = ("Source Link,Company Link,company name")
    f.write(headers)
    f.write("\n")
    for ip in content1:
        chrome_options.add_argument('--proxy-server=%s' % ip)
        try:
            for link in content:

                    try:
                        browser.get(link)
                        browser.implicitly_wait(4)
                        abba = browser.find_element_by_css_selector('.WebToolsetToolWebPart_Cntnr.WebToolsetToolWebPart_Aligned_LEFT.WebToolsetToolWebPart_TxtTool_Cntnr')
                        aas = abba.text
                        aa = aas.replace(",","")
                        print(ip + "," + link + "," + aa)
                        f.write(link + "," +aa+"\n")

                    except NoSuchElementException:
                        aa = "no count available"
                        print(ip + ","+link + "," + aa)
                        f.write(link + "," + aa + "\n")
        except StaleElementReferenceException:
            pass

Tags: inipbrowsertxtforaswithlink
1条回答
网友
1楼 · 发布于 2024-10-01 13:26:05

保存内部循环索引,如果此错误仍然存在,请参阅currentIndex了解其工作方式。你知道吗

with open('E:\Master\master1.csv', 'a') as f:
    headers = ("Source Link,Company Link,company name")
    f.write(headers)
    f.write("\n")

    currentIndex = 0
    for ip in content1:
        chrome_options.add_argument(' proxy-server=%s' % ip)
        try:
            for link in content[currentIndex:]: # start from 0 or continue from last index error
                try:
                    browser.get(link)
                    browser.implicitly_wait(4)
                    abba = browser.find_element_by_css_selector('.WebToolsetToolWebPart_Cntnr.WebToolsetToolWebPart_Aligned_LEFT.WebToolsetToolWebPart_TxtTool_Cntnr')
                    aas = abba.text
                    aa = aas.replace(",","")
                    print(ip + "," + link + "," + aa)
                    f.write(link + "," +aa+"\n")

                except NoSuchElementException:
                    aa = "no count available"
                    print(ip + ","+link + "," + aa)
                    f.write(link + "," + aa + "\n")
                    break # stop this inner loop and continue outer loop

                # current loop is good save the next index
                currentIndex += 1

            # if it last index of "content", reset the index <- minor fix
            if currentIndex == len(content) - 1:
                currentIndex = 0

        except StaleElementReferenceException:
            pass 

相关问题 更多 >