在 Beautiful Soup 中,標簽或字符串的 next_siblings
屬性返回一個生成器,用於迭代同一父級下的所有後續標簽和字符串。
例子
考慮以下 HTML 文檔:
my_html = """
<div>
<p>Alex</p>
<p>Bob</p>
</div>
"""
soup = BeautifulSoup(my_html)
讓我們獲取 <p>Alex</p>
的 next_siblings
:
p_alex = soup.find("p")
for s in p_alex.next_siblings:
print(repr(s))
'\n'
<p>Bob</p>
'\n'
<p>Cathy</p>
'\n'
在這裏,我們使用 repr(~)
方法來轉義換行符,以便您可以顯式看到 '\n'
而不是空行。為了解決這個問題,<p>Alex</p>
的 next_sibling
是一個換行符,這對於那些希望看到 <p>Bob</p>
的人來說可能會感到驚訝。出現這樣的結果是因為 <p>Alex</p>
和 <p>Bob</p>
之間存在換行符 \n
。
如果您隻想訪問下一個同級元素,那麽更好的選擇是調用 find_next_siblings()
方法:
p_alex = soup.find("p")
for s in p_alex.find_next_siblings():
print(repr(s))
<p>Bob</p>
<p>Cathy</p>
相關用法
- Python BeautifulSoup next_sibling屬性用法及代碼示例
- Python BeautifulSoup next_element屬性用法及代碼示例
- Python BeautifulSoup next_elements屬性用法及代碼示例
- Python next方法用法及代碼示例
- Python next()用法及代碼示例
- Python networkx.algorithms.shortest_paths.weighted.all_pairs_dijkstra_path用法及代碼示例
- Python networkx.classes.function.edge_subgraph用法及代碼示例
- Python networkx.algorithms.tree.mst.maximum_spanning_edges用法及代碼示例
- Python networkx.algorithms.bipartite.basic.color用法及代碼示例
- Python networkx.algorithms.bipartite.cluster.latapy_clustering用法及代碼示例
- Python networkx.readwrite.json_graph.adjacency_data用法及代碼示例
- Python networkx.algorithms.bipartite.edgelist.generate_edgelist用法及代碼示例
- Python networkx.Graph.neighbors用法及代碼示例
- Python networkx.DiGraph.__contains__用法及代碼示例
- Python networkx.drawing.nx_pylab.draw_random用法及代碼示例
- Python networkx.convert_matrix.to_pandas_edgelist用法及代碼示例
- Python networkx.DiGraph.__init__用法及代碼示例
- Python networkx.algorithms.cycles.recursive_simple_cycles用法及代碼示例
- Python networkx.drawing.layout.random_layout用法及代碼示例
- Python networkx.algorithms.link_prediction.within_inter_cluster用法及代碼示例
- Python networkx.algorithms.non_randomness.non_randomness用法及代碼示例
- Python networkx.algorithms.traversal.depth_first_search.dfs_tree用法及代碼示例
- Python networkx.MultiGraph.clear用法及代碼示例
- Python networkx.algorithms.operators.product.cartesian_product用法及代碼示例
- Python networkx.algorithms.traversal.depth_first_search.dfs_labeled_edges用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 BeautifulSoup | next_siblings property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。