Beautiful Soup 的 new_tag(~)
方法创建一个新标签,然后我们可以将其插入到解析树中。
参数
1. tag name
| string
标签的名称。
2. attribute
| attribute
| optional
新标签的属性。默认为 None
。
例子
考虑以下 HTML 文档:
my_html = """
<div>
<p>Alex</p>
<p id="bob">Bob</p>
<p>Cathy</p>
</div>
"""
soup = BeautifulSoup(my_html)
标签名
要创建新标签:
# Create a new tag and initialise it's content
new_tag = soup.new_tag("p")
new_tag.string = "Eric"
要将其附加到现有的 "Bob"
标记:
bob_tag = soup.find("p", {"class": "Bob"})
bob_tag.append(new_tag)
print(soup.find("div"))
<div>
<p id="alex">Alex</p>
<p class="Bob">Bob<p>Eric</p></p>
<p id="cathy">Cathy</p>
</div>
要在 "Bob"
标记之前插入新标记:
bob_tag = soup.find("p", {"class": "Bob"})
bob_tag.insert_before(new_tag)
print(soup.find("div"))
<div>
<p id="alex">Alex</p>
<p>Eric</p><p class="Bob">Bob</p>
<p id="cathy">Cathy</p>
</div>
要在 "Bob"
标记后插入新标记:
bob_tag = soup.find("p", {"class": "Bob"})
bob_tag.insert_after(new_tag)
print(soup.find("div"))
<div>
<p id="alex">Alex</p>
<p class="Bob">Bob</p><p>Eric</p>
<p id="cathy">Cathy</p>
</div>
属性
要创建具有 href
属性的新 "a"
标记:
# Create a new tag and initialise it's content
new_tag = soup.new_tag("a", href="http://www.skytowner.com")
new_tag.string = "Sky Towner"
print(new_tag)
<a href="http://www.skytowner.com">Sky Towner</a>
相关用法
- 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 next方法用法及代码示例
- 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用法及代码示例
- Python networkx.DiGraph.number_of_edges用法及代码示例
- Python networkx.algorithms.tree.operations.join用法及代码示例
- Python networkx.generators.random_graphs.random_shell_graph用法及代码示例
- Python networkx.classes.function.is_weighted用法及代码示例
注:本文由纯净天空筛选整理自Arthur Yanagisawa大神的英文原创作品 BeautifulSoup | new_tag method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。