python - 使用选择器获取不同 "h"标签的内容时遇到问题

标签 python python-3.x web-scraping beautifulsoup css-selectors

我正在尝试从多个 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/

相关文章:

python - Beautiful Soup 不返回 html 表的列表

python - 如何使用 epoll 和 python 3.1 进行异步 http 请求

node.js - 使用 jsdom 时出现 "Dispatching event ' DOMNodeInsertedIntoDocument' failed"错误

javascript - 使用 chromedp,从 *runtime.RemoteObject 中获取一个 javascript 对象/数组

python - 如何正确使用 ShowWIndow() 和 SetForegroundWindow?

python - 我可以在没有任何给定函数形式的情况下使用 Python 中的多变量数据框运行非线性回归吗?

python-3.x - PyCharm 2019.1 CE : No option to create/edit Jupyter Notebook (*. ipynb)文件?

r - 有没有办法在原始数据中添加文本(链接)?

python - 无法更新在 Google Cloud Platform 上构建的网站

python - 如何使用 TOR 和 Stem 以及 python 打造新身份?与(tor浏览器)新身份完全相同