【问题标题】:Python for loop always uses else statementPython for 循环总是使用 else 语句
【发布时间】:2019-05-25 11:27:23
【问题描述】:

我正在编写一个程序来检测带有打印的 404 页面。要检测这些页面,我会使用数组列表中的名称来填充 url,例如 --> steamcommunity.com/groups/(ARRAY FILLED)。

from bs4 import BeautifulSoup
import requests
import json

names = json.loads(open('names.json').read())

def groupfinder():
    for name in names:
        url = requests.get('https://steamcommunity.com/groups/').text + name
        soup = BeautifulSoup(url, 'lxml')
        clan = soup.find('span', class_='grouppage_header_abbrev')
        clantag = clan
        if clan != None:
            print(clantag.text,"is already taken")
        else:
            print('GROUP FOUND',name)

groupfinder()

for 循环中的代码应该在每个数组名称上运行,但它只是坚持 else 语句。当所有组在域中时,它会输出所有组都已找到。

soup find 正在搜索所有声明的 url 所具有的组的名称。我正在寻找一个无人认领的。

【问题讨论】:

  • 旁注,更pythonic应该是if clan is not None
  • 如果只有else 会触发,那是因为if-test,无论您期望什么,总是错误。换句话说,soup.find() 在您认为不应该返回的情况下返回 []。在soup.find() 调用之后添加一行print(clan),这样您就可以看到发生了什么。

标签: python loops beautifulsoup


【解决方案1】:

您面临的问题与您使用的 URL 相关联。就像现在一样:

url = requests.get('https://steamcommunity.com/groups/').text + name

您正在向https://steamcommunity.com/groups/(每次)发送一个 GET 请求,并将氏族名称 (name) 附加到 HTML 文本的末尾。

你应该用这一行替换整行:

url = requests.get('https://steamcommunity.com/groups/' + name).text

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 2016-10-28
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多