python3访问bs4元素的索引行

时间:2017-10-18 12:04:36

标签: python python-3.x beautifulsoup

我有一个bs4对象,并使用findAllfind_next_sibling选择其中的一部分。从这个我称之为“兄弟姐妹”的部分,我用这样的for循环访问每一行:

for cursor in sibling:
    index = sibling.index(cursor)
    print(index)          # works until here
    next_cursor = sibling[index+1]
    print(next_cursor)    # breaks with KeyError

有谁知道我在这里缺少什么?

2 个答案:

答案 0 :(得分:1)

假设我了解你的情况,我可以建议一种更简单的方法来解决这个问题。

假设你有这样的HTML。

<span id="first">I'm first</span>
<span>first sibling</span>
<span>second sibling</span>
<span>third sibling</span>
<span>fourth sibling</span>
<span>fifth sibling</span>

然后你可以找到第一个span元素,然后使用这样的代码识别它的所有兄弟姐妹。

>>> import bs4
>>> soup = bs4.BeautifulSoup(open('temp.htm').read(), 'lxml')
>>> first = soup.select('#first')
>>> first
[<span id="first">I'm first</span>]

此行仅用于显示findNextSiblings方法为您提供的内容。

>>> first[0].findNextSiblings()
[<span>first sibling</span>, <span>second sibling</span>, <span>third sibling</span>, <span>fourth sibling</span>, <span>fifth sibling</span>]

这意味着,一旦你有一个指向第一个兄弟的指针,你可以用一个for语句获得所有其他兄弟。

>>> for sib in first[0].findNextSiblings():
...     sib.text
... 
'first sibling'
'second sibling'
'third sibling'
'fourth sibling'
'fifth sibling'

另一种方法fetchNextSiblings提供与上面使用的方法相同的结果。

>>> first[0].fetchNextSiblings()
[<span>first sibling</span>, <span>second sibling</span>, <span>third sibling</span>, <span>fourth sibling</span>, <span>fifth sibling</span>]

答案 1 :(得分:0)

您使用BeautifulSoup创建的兄弟姐妹无法像这样逐行阅读。

兄弟姐妹的类型为bs4.element.Tag。如果要逐行读取它,必须将其转换为字符串,然后在其上调用def saveImg(event): global canvas canvas.postscript(file="my_drawing.eps", colormode='color') imgNew = Image.open("my_drawing.eps") imgNew.convert("RGBA") imgNew.thumbnail((2000,2000), Image.ANTIALIAS) imgNew.save('testImg.png', quality=90)

像这样:

.splitlines()