使用BeautifulSoup获取标签名称

vjg*_*ero 2 python beautifulsoup

from bs4 import BeautifulSoup
source_code = """<a href="#" name="linkName">ok</a>"""
soup = BeautifulSoup(source_code)
print soup.a.? #find the object name
Run Code Online (Sandbox Code Playgroud)

使用上面显示的代码,我试图打印锚标签的名字',这是linkName,但我不知道哪个模块或对象,我会使用,我都试过contentsnametag_name_re

有人可以帮我吗?谢谢!

小智 5

您已经回答了问题。

soup.a['name']
Run Code Online (Sandbox Code Playgroud)

编辑

如果您有多个a元素,则可以执行以下操作:

x = """<x><a name="foo"/><a name="bar"/></x>"""
s = bs4.BeautifulSoup(x)
for a in s.findChildren("a"):
    print(a["name"])
Run Code Online (Sandbox Code Playgroud)