簡體   English   中英

在不同時間滿足條件時停止 python for 循環

[英]Stop a python for loop when conditions are met at different times

以下是我用 python 編寫的簡單代碼,用於從數字升序的 URL 中抓取特定信息。 效果很好,我可以在 python IDLE 中看到結果。

import requests
from urllib import request, response, error, parse
from urllib.request import urlopen
from bs4 import BeautifulSoup

for i in range(35, 345, 1):
    url = 'https://www.example.com/ID=' + str(i)
    html = urlopen(url)
    soup = BeautifulSoup(html, "html.parser")
    information1=soup.find(text='sam')
    information2=soup.find(text='john')
    print(information1,information2,i)

所以結果是這樣的:

None None 35
None None 36
None sam 37
john None 38
None None 39
....
None None 345

現在這很棒,也是我所需要的,但是我想通過在找到我需要的一切時在“john None 38”處停止執行來改進我的代碼。 所以不會有不必要的額外 300 多行。

現在有兩件事你應該知道。 首先,information1 和information2 永遠不會在同一個網頁中。 它們將始終位於不同的 URL 上。 其次,在上面的代碼中,信息 1 首先出現在信息 2 之前,但如果我將字符串更改為我正在尋找的其他內容,則相反的情況也是可能的。

因此,該解決方案需要結合這樣一個事實,即信息 1 和信息 2 將出現在不同行的結果中,並且信息 1 可能首先出現或第二次出現,反之亦然。

我真的很難用上述條件形成“if”代碼。 我很感激任何幫助。 謝謝你。

# Default to None
information1 = None
information2 = None
for i in range(35, 345, 1):
    ...
    # If already set don't override
    information1 = information1 or soup.find(text='sam')
    # Same here
    information2 = information2 or soup.find(text='john')
    if information1 and information2:
        # We have both information1 and information2 so break out of the for loop
        break

您可以將跟蹤器存儲在循環之外,並在迭代之間保留它們:

import requests
from urllib import request, response, error, parse
from urllib.request import urlopen
from bs4 import BeautifulSoup

info1 = None
info2 = None

for i in range(35, 345, 1):
    url = 'https://www.example.com/ID=' + str(i)
    html = urlopen(url)
    soup = BeautifulSoup(html, "html.parser")
    information1=soup.find(text='sam')
    information2=soup.find(text='john')

    if information1 is not None and info1 is None:
        info1 = information1

    if information2 is not None and info2 is None:
        info2 = information2

    if info1 and info2:
        break

print('Information 1: {}'.format(info1))
print('Information 2: {}'.format(info2))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM