【问题标题】:python3 access bs4 element's lines with indexpython3使用索引访问bs4元素的行
【发布时间】:2017-10-18 12:04:36
【问题描述】:

我有一个 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

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

【问题讨论】:

    标签: python python-3.x beautifulsoup


    【解决方案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>]
    

    【讨论】:

    • 感谢您的建议。我可以通过访问兄弟 [index+2] 而不是 index+1 来解决我的问题。内容嵌套在
      括号中,当我使用 index+1 时,我访问了这些括号。
    • 不客气。我这样回答是因为我认为你可能会觉得它很有用,但我不知道你在解决什么问题。
    • 其实我没有意识到那些
      括号组成了自己的一行。我认为它们是我正在查看的线条的一部分。
    • @Ollie:也许你应该停止在行中思考,因为 BeatifulSoup 不是在行上操作,而是在对象树上操作。
    【解决方案2】:

    你用 BeautifulSoup 创建的兄弟不能像这样逐行读取。

    兄弟的类型是 bs4.element.Tag。如果您想逐行阅读,则必须将其转换为字符串,然后在其上调用.splitlines()

    像这样:

    for line in str(sibling).splitlines():
        ...
    

    【讨论】:

    • 感谢您的评论。不需要分割行,因为 for 循环是逐行访问内容。
    猜你喜欢
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 2018-03-17
    • 2020-02-18
    • 2017-04-23
    相关资源
    最近更新 更多