Python BeautifulSoup是不必要的

2024-09-28 21:00:06 发布

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

虽然这段代码运行得相当快:

for olay in soup("li", {"class":"textb"}):
    tanim = olay("strong")
    try:
        print tanim[0]
    except IndexError:
        pass

像这样获取字符串属性会使此代码的速度大大降低:

^{pr2}$

我的问题是,我是不是在做一些不该得到字符串属性的事情?我应该使用其他方法来获取对象的纯文本版本吗?在

更新: 这也是相当快的工作,所以慢是唯一的字符串属性,我猜?在

for olay in soup("li", {"class":"textb"}):
    tanim = olay("strong")
    try:
        print tanim[0].text
    except IndexError:
        pass

Tags: 字符串infor属性liclassstrongprint
1条回答
网友
1楼 · 发布于 2024-09-28 21:00:06

如果您只想打印tanim[0]的字符串表示。你应该这样做:print str(tanim[0])。另外,执行一个dir(tanim[0]),看看它是否有一个名为string的属性。在

for olay in soup("li", {"class":"textb"}):
    tanim = olay("strong")
    try:
        print str(tanim[0])
    except IndexError:
        pass

为了让每个人都能提供更好的答案,您还可以发布目标HTML或URI,并指出您要从中提取哪个位。在

相关问题 更多 >