【问题标题】:Finding labels together with ids in html tags using Python使用 Python 在 html 标签中查找标签和 id
【发布时间】:2021-11-17 02:22:01
【问题描述】:

我用selenium提取了一个网站的html代码,我把它放在了变量html_code中

我想提取那些html标签的标签和对应的id。

到目前为止,我已经设法单独使用提取标签

var1 = re.findall(r'<label\s*.*>(.+?)<\?label>', html_code)

我的问题是:如何将html标签的相应ID与标签一起提取?我使用什么功能?我可以为此使用 findall 或其他功能的组合吗?

【问题讨论】:

  • 什么是标签ID?
  • 上传 HTML sn-p 并解释预期的输出。
  • 在 HTML 上使用正则表达式是 ill-advised。使用 BeautifulSoup 之类的 HTML 解析器,您尝试做的事情听起来是可行的
  • @balder 下面是我要处理的 HTML sn-p 示例: I需要将 id_name 和 LabelName 一起提取并放入 pandas 数据框
  • @WiktorStribizew 请参考我上面的评论

标签: python html regex


【解决方案1】:

你可以使用 Beautifulsoup 来提取你需要的细节:

from bs4 import BeautifulSoup
soup = BeautifulSoup(r'<label id="id_name" for="whichever" class="class_name">LabelName</label>')
l = soup.find('label')
l.text
# => 'LabelName'
l["id"]
# => 'id_name'

使用soup.find('label'),您将获得对象,即soup 对象中名称为label 的第一个节点。

l.text 获取节点的文本(内部文本)值,l["id"] 获取id 属性值。

【讨论】:

  • 谢谢。它工作得非常好。现在我有另一个问题,我需要问一个不同的问题。
  • @Tipo33 如果和这个页面解析关系密切,最好在cmets这里问。
  • 我希望记录页面上按钮的 ID 和文本。然后,对于每个按钮,我想在其子菜单中记录每个按钮的 ID 和文本。我需要它们可能是图形数据库样式,以便爬虫可以访问这些页面中的每一个。
  • @Tipo33 然后你只需要soup.find_all('button') 或类似的东西,然后你就可以遍历找到的节点,并获取你需要的数据。
【解决方案2】:

见下文。这个想法是使用 XML 解析器“查看”html。

import xml.etree.ElementTree as ET
import pandas as pd


html = '''<html>
              <label id="id_name1" for="whichever" class="class_name">LabelName1</label>
              <label id="id_name2" for="whichever" class="class_name">LabelName2</label>
          </html>'''

data = []
root = ET.fromstring(html)
for l in root.findall('label'):
    data.append({'id':l.attrib['id'],'text':l.text})
df = pd.DataFrame(data)
print(df)

输出

         id        text
0  id_name1  LabelName1
1  id_name2  LabelName2

【讨论】:

  • 我设法使用 Beautiful Soup 找到了我的解决方案。感谢您在此解决方案中为我提供的帮助。谢谢
猜你喜欢
  • 1970-01-01
  • 2013-09-18
  • 1970-01-01
  • 1970-01-01
  • 2017-06-14
  • 2021-01-25
  • 1970-01-01
  • 2020-03-19
  • 1970-01-01
相关资源
最近更新 更多