python - 使用 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
解决方案
与其逐个类地迭代,不如不顾类地从上到下遍历整个 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")
推荐阅读
- ruby - 如何从特定点获取对角线值?
- oracle - 无论精度如何,Toad 都会截断尾随的“0”十进制数字
- c - 在 macOS Mojave 中使用 gcc 编译
- python - AttributeError:“builtin_function_or_method”对象没有属性“fieldnames”
- python - 壁虎驱动问题
- java - 更新集
如果 Person 存在,或者如果不存在则添加它们 - javascript - Reduxjs 或简单地声明
- c++ - 在 noexcept 规范中是否允许使用 `this`?
- spring - Spring post方法“缺少所需的请求正文”
- java - 在 Windows 7 中绕过 System32 / SysWOW64 javaw.exe 从 VBA 宏运行 java