我在python中从列表中获取第一个元素的if语句不起作用

2024-10-02 06:30:13 发布

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

嗨,我是python的新手,我用漂亮的汤创建了我的第一个程序 我要使用的if语句。我想看看第一个元素是否正确。我遇到一个语法错误,我还没想好怎么解决它。这是我对代码的最后一次迭代,在迭代剩余元素之前,我添加了一个头

Mycurrent Output with current CodePage that I'm using scraper on

import requests
from bs4 import BeautifulSoup

req = requests.get("http://espn.go.com/college-football/rankings")

soup = BeautifulSoup(req.content, "lxml")

g_data = soup.find_all("tr")
myCaptions = soup.find_all("caption")
print "Here are the college-football Rankings for 2015"

if myCaptions[0]:
    print "College Football Playoff Rankings" #Lets print the first header

for rows in g_data:

    contro = 0
    try:
        ranking = rows.contents[0].find_all("span")[0].text
        myTeam = rows.contents[1].find_all("span", {"class": "team-names"})[0].text
        myRecord = rows.find_all("td")[2].text
        print ranking + "  " + myTeam + " " + myRecord
    except:
        pass
    contro = contro + 1

Tags: textimport元素ifallfindrequestsreq
1条回答
网友
1楼 · 发布于 2024-10-02 06:30:13

首先,您有一个缩进错误-^{cd1>}由于某种原因奇怪地缩进。

此外,如果您想检查值的真实性,则无需显式地将其与^{{cd2>}进行比较,只需使用^{{cd3>}。


无论如何,首先不需要^{cd4>}如果您想检查是否找到元素。相反,使用^{{cd5>}检查结果是否不是^{cd6>}:

caption = rows.find("caption")        
if caption is not None:  # "if caption:" would also work
    print "College Football Playoff Rankings"

下面是如何处理如何查找带标题的多个表的问题:

^{pr2}$

适用于我,打印:

^{pr3}$

相关问题 更多 >

    热门问题