如何跳过对一个for循环中不存在于一页或多页中的标记的刮取?

2024-09-24 22:18:45 发布

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

我在一些页面中循环,从<a>标记中刮出文本。我使用的是python3.7。你知道吗

除了一个页面没有我正在刮的<a>标签外,其他的一切都很顺利。我希望能够从每个页面的<a>标记中提取所需的文本,并在没有标记的页面之后继续脚本。你知道吗

我试图用“如果没有”来回避这个问题。但我没能让它发挥作用。你知道吗

这会导致属性错误:“NoneType”对象没有属性“a”

p = indaplaybox.div.a
P_O = p.text if p else None
print(P_O)

indaplaybox的普通HTML如下所示:

<tr class="pncPlayerRow playerTableBgRow1" id="plyr17676">
    <td class="slot_4 playerSlot" id="slot_17676" style="font-weight: bold;">WR</td>
    <td class="playertablePlayerName" id="playername_17676" style=""><a cache="true" class="flexpop" content="tabs#ppc" fpopheight="357px" fpopwidth="490px" href="" instance="_ppc" leagueid="216415" playerid="17676" seasonid="2018" tab="null" teamid="-2147483648">StefD</a>, Mn WR</td>
    <td>
        <div><a class="flexpop" content="ajax#/ffl/format/pvopop/summary?leagueId=216415&amp;positionId=3&amp;playerId=70325&amp;seasonId=2018" instance="_ppc">SF</a></div>
    </td>
    <td class="gameStatusDiv"><span class="gameNotch_380909016_16 onFieldNotch">»</span> <a class="gamestatus_380909016_16" target="_blank">W 24-16</a></td>
    <td class="playertableStat">12.6</td>
</tr>

导致错误的HTML如下所示:

<tr class="pncPlayerRow playerTableBgRow0" id="plyr18225">
    <td class="slot_2 playerSlot" id="slot_18225" style="font-weight: bold;">RB</td>
    <td class="playertablePlayerName" id="playername_18225" style=""><a cache="true" class="flexpop" content="tabs#ppc" fpopheight="357px" fpopwidth="490px" instance="_ppc" leagueid="216415" playerid="18225" seasonid="2018" tab="null" teamid="-2147483648">Kareem Hunt</a>, FA RB</td>
    <td align="center" colspan="2">** BYE **</td>
    <td class="playertableStat appliedPoints appliedPointsProGameFinal">4.9</td>

谢谢你的帮助!你知道吗


Tags: instance标记文本dividstyle页面content
1条回答
网友
1楼 · 发布于 2024-09-24 22:18:45

由于没有给出完整的代码,它限制了如何回答。但我会用try

它将尝试设置p = indaplaybox.div.a。如果不能,它只会继续到列表中的下一个元素

try:
    p = indaplaybox.div.a
    P_O = p.text
    print(P_O)

except:
    print ("no attribute 'a'")
    continue

相关问题 更多 >