在 Beautiful Soup 中,next_element
屬性返回解析樹中的下一個 string
或 tag
。我們將通過示例來了解此屬性的微妙之處。
例子
考慮以下 HTML 文檔:
my_html = """
<p>Alex</p>
<p>Bob</p>
"""
soup = BeautifulSoup(my_html)
讓我們獲取 <p>Alex</p>
的 next_element
:
p_alex = soup.find("p")
p_alex.next_element
'Alex'
請注意內部字符串如何注冊為下一個元素。這裏的要點是順序是從標簽到內部字符串。
讓我們計算'Alex'
字符串的next_element
:
p_alex = soup.find("p")
p_alex.next_element.next_element
'\n'
對於那些期望看到 <p>Bob</p>
的人來說,結果可能會令人驚訝。出現這樣的結果是因為 <p>Alex</p>
和 <p>Bob</p>
之間存在換行符 \n
。那麽,要聯係 Bob,您需要再次調用 next_element
:
p_alex = soup.find("p")
p_alex.next_element.next_element.next_element
<p>Bob</p>
如果您隻想訪問下一個同級元素,那麽更好的選擇是調用 find_next_sibling()
方法:
p_alex = soup.find("p")
p_alex.find_next_sibling()
<p>Bob</p>
相關用法
- Python BeautifulSoup next_elements屬性用法及代碼示例
- Python BeautifulSoup next_sibling屬性用法及代碼示例
- Python BeautifulSoup next_siblings屬性用法及代碼示例
- 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_element property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。