如果条件为真,如何重复代码

问题描述 投票:0回答:1

我有这个代码:

from typing import Text
import tweepy
import random

from tweepy import Response, tweet
client = tweepy.Client(
    consumer_key="XXXXXX",
    consumer_secret="XXXXXX",
    access_token="XXXXXX",
    access_token_secret="XXXXXX"
)

import requests
from bs4 import BeautifulSoup
import webbrowser

while True:
    url = requests.get("https://he.wikipedia.org/wiki/Special:Random")
    soup = BeautifulSoup(url.content, "html.parser")
    title = soup.find(class_="firstHeading").text
    printed = print(title)
    break
try:
   client.create_tweet(text="לשטח את " + title)
   print("וואלה יופי הצלחת יא בתול")
   print("יא קינג יא אלוף אין עליך יא גאון מחשבים")
except tweepy.errors.TweepyException as e:
   print("שגיאה על הראש שלך")
   print("יא אפס")

我想使用这个条件:

if 'משתמש' in title:
,如果条件为真,则重试代码,因此它会尝试打印另一个标题,直到条件不为真。

python twitter tweepy wikipedia
1个回答
0
投票

您已经创建了一个 while 循环来尝试获取 url,但在代码块的末尾,您总是会跳出循环。即使你没有得到回应。

因此,在休息前添加您的(已提供的)条件,如下所示:

while True:
    url = requests.get("https://he.wikipedia.org/wiki/Special:Random")
    soup = BeautifulSoup(url.content, "html.parser")
    title = soup.find(class_="firstHeading").text
    printed = print(title)
    if 'משתמש' in title:
        break

此外,您不应该将变量分配给 print 语句,它只会返回 None,因此将该行更改为:

print(title)

而不是:

printed = print(title)
© www.soinside.com 2019 - 2024. All rights reserved.