我正在尝试从多个 h
中获取不同的标题来自一些 html 元素的标签。 h
标签总是附有一些数字,如h1
, h14
, h17
。我知道我可以利用.select("h1,h11,h9")
去拿它们,但它们数量很多。我可以使用.select("[class^='heading']")
来处理它们如果它们类似于 class="heading1"
, class="heading2"
, class="heading3"
。
如何获取不同 h
的所有内容使用选择器标记?
我的尝试:
htmlelements="""
<h1>
<a href="https://somesite.com/">SEC fight</a>
</h1>
<h11>
<a href="https://somesite.com/">AFC fight</a>
</h11>
<h9>
<a href="https://somesite.com/">UTY fight</a>
</h9>
"""
from bs4 import BeautifulSoup
page = BeautifulSoup(htmlelements, "lxml")
for item in page.select("h11"):
print(item.text)
PS 正则表达式不是一个选项 .find_all(string=re.compile("h"))
在这里。
最佳答案
一种方法是仅对所有可能的 h
标记使用 .find_all()
:
htmlelements="""
<h1>
<a href="https://somesite.com/">SEC fight</a>
</h1>
<h11>
<a href="https://somesite.com/">AFC fight</a>
</h11>
<h9>
<a href="https://somesite.com/">UTY fight</a>
</h9>
"""
from bs4 import BeautifulSoup
page = BeautifulSoup(htmlelements, "lxml")
for item in page.find_all(f"h{h}" for h in range(1, 20)):
print(item.get_text(strip=True))
这将显示:
SEC fight
AFC fight
UTY fight
关于python - 使用选择器获取不同 "h"标签的内容时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54920381/