我正在抓取网页,并且每隔几秒就会更改某个变量minute
。此minute
位于永久运行的def
内。如果,例如,minute == 80
,if语句只运行一次,我怎么能这样做呢?
以下是代码的外观:
def login(): # necesarry for this
// stuff
return r
def run(r):
//stuff
minute_soup = soup.find_all("span", {"class":"clock-period"})
minute = minute_soup[0].text
if minute == 80:
print(minute)
time.sleep(10)
r = login()
while True:
run(r)
目前,每次minute
等于80时,它会一次又一次地做同样的事情,每隔10秒才会minute
不等于80.有什么方法可以做minute
等于80时的一次?
答案 0 :(得分:1)
您可以使用该参数来保存标志:
def run(r):
//stuff
minute_soup = soup.find_all("span", {"class":"clock-period"})
minute = minute_soup[0].text
if minute == 80 and r.flag:
r.flag = False
print(minute)
if minute != 80:
r.flag = True
time.sleep(10)
r = login()
r.flag = True
while True:
run(r)
答案 1 :(得分:0)
正如我从您的问题中所理解的,您可以使用from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url = 'https://www.realtor.ca/Residential/map.aspx#CultureId=1&ApplicationId=1&RecordsPerPage=9&MaximumResults=9&PropertySearchTypeId=1&TransactionTypeId=2&StoreyRange=0-0&BedRange=0-0&BathRange=0-0&NumberofDays=4&LongitudeMin=-122.8479843139653&LongitudeMax=-122.68181610107467&LatitudeMin=49.244425437286374&LatitudeMax=49.303560989620294&SortOrder=A&SortBy=1&viewState=l&Longitude=-122.76490020752&Latitude=49.2740020751953&CurrentPage=1&ZoomLevel=13&PropertyTypeGroupID=1'
#opening up connection, grabbing the page
uClient = uReq(my_url)
page_content = uClient.read()
uClient.close()
#html parsing
content_soup = soup(page_content, "html.parser")
,当第一时间分钟变为flag
时,将其设置为true,则80
将永远不再执行:
if
答案 2 :(得分:0)
这将是这样的:
flag = true
def run(r):
if r == 80:
if flag:
flag = false
//More stuff
else:
flag = true
我建议你研究一下事件处理,因为无限循环通常可以通过使用导致代码更清晰的事件来解决
答案 3 :(得分:-1)
minuteRunOnce = False
def run(r):
//stuff
minute_soup = soup.find_all("span", {"class":"clock-period"})
minute = minute_soup[0].text
if (minute == 80 and not(minuteRunOnce)):
print(minute)
minuteRunOnce = True
time.sleep(10)
r = login()
while True:
run(r)