首页 > 解决方案 > 使用 Decompose 删除空标签

问题描述

我正在尝试在 HTML 元素中搜索电子邮件。我想运行代码,以便当在 HTML 中找不到电子邮件时,在 HTML 中的另一个元素中搜索,最后如果找不到将电子邮件设置为“N/A”。

我是编写代码的新手,我正在尝试为一个项目的培训练习做这件事。

这是我试图分解并从中提取电子邮件的 HTML:

<div class="Profile-sidebar">
   <div class="Profile-header">
      <div class="Profile-userDetails">
         <p class="Profile-line"><a class="Profile"> Search Location No.1</a></p>
      </div>
   </div>
   <div class="UserInfo" style="">
      <div class="UserInfo">
         <div class="UserInfo-Header">
            <h5 class="UserInfo-Title">About</h5>
         </div>
         <div class="UserInfo-column">
            <p class="UserInfo-bioHeader">About</p>
            <div class="UserInfo"><span>Search Location No.2</span></div>
         </div>
      </div>
   </div>
</div>

这是 python 代码,我在从 bio 中提取文本后创建了一个空列表,我搜索电子邮件,如果标签为空,它会分解标签:

email_list = []
    bio = soup.find('div', {'class': 'UserInfo'}).text
    for my_tag in soup.find_all(class_="UserInfo"):
        EMAIL_REGEX = "[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+"
        emails = re.findall(EMAIL_REGEX, my_tag.text)
        if not my_tag.text:  # if tag is empty
            my_tag.decompose()
            print(emails)

我收到的结果print(emails),如果我试图摆脱的 for 循环中没有电子邮件:

[]
[]
[]

我的问题:

我正在分解的 HTML 在同一标签下具有类似的类。我的问题是我只想知道如何从具有特定类的一个元素中搜索,如果没有找到结果,则在具有另一个类的另一个元素中进行搜索,最终而不是接收[] [] []成为N/A

标签: pythonbeautifulsoup

解决方案


与其逐个类地迭代,不如不顾类地从上到下遍历整个 HTML,如果找到 EMAIL,只需将 EMAIL 与元素的类一起存储在字典中。然后,您可以根据要首先检查的课程从字典中查找电子邮件。

EMAIL_REGEX = "[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+"
def applyRegex(element):
    if element.text:
       emailsFound = re.findall(EMAIL_REGEX, element.text)
       if emailsFound:
          return True
   return False


final_dict = {}
email_elements = soup.find_all(applyRegex)

for element in email_elements:
   emailsFound = re.findall(EMAIL_REGEX, element.text)
   for email in emailsFound:
      if element.has_attr('class'):
         classname = element['class']
         final_dict.update({classname: element.text})

if final_dict:
   # do whatever you want to do with the dictionary of <class>:<email>
else:
   print("N/A")

推荐阅读