我正在尝试从某些html元素的多个h
标记中获取不同的标题。 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 regex在这里不是.find_all(string=re.compile("h"))
选项。
参考方案
一种方法是只对所有可能的.find_all()
标签使用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.find_all(f"h{h}" for h in range(1, 20)):
print(item.get_text(strip=True))
这将显示:
SEC fight
AFC fight
UTY fight
Python ElementTree:在循环中替换元素 - python我正在尝试创建一个脚本,该脚本循环创建一个xml文件,并为两个元素增加值。 (使用netaddr的IP地址,以及递增的tag / member元素,tag01-tag10)from netaddr import IPNetwork import xml.dom.minidom import lxml.etree as etree import xml.etr…
Python Pandas导出数据 - python我正在使用python pandas处理一些数据。我已使用以下代码将数据导出到excel文件。writer = pd.ExcelWriter('Data.xlsx'); wrong_data.to_excel(writer,"Names which are wrong", index = False); writer.…
将python scikit学习模型导出到pmml - python我想将python scikit-learn模型导出到PMML。哪个python软件包最合适?我阅读了有关Augustus的内容,但是我无法使用scikit-learn模型找到任何示例。 python大神给出的解决方案 SkLearn2PMML是 JPMML-SkLearn命令行应用程序周围的薄包装。有关受支持的Scikit-Learn Estimator和…
Python:检查是否存在维基百科文章 - python我试图弄清楚如何检查Wikipedia文章是否存在。例如,https://en.wikipedia.org/wiki/Food 存在,但是https://en.wikipedia.org/wiki/Fod 不会,页面只是说:“维基百科没有此名称的文章。”谢谢! 参考方案 >>> import urllib >>> prin…
按列名称显示的Python Selenium复制表列 - python我有一个包含这些标题的表,如下所示:如何使用xpath选择整列存储在数组中。我希望使用不同的数组,例如:courses = [] teacher = [] avg = [] 请记住,这些列没有任何ID或类,因此我需要一种仅使用列名进行选择的方法。这是表格的代码:<table border="0"> <tbody> …