python - 如何检查 <a href> 元素是否存在于 <div> 元素中?

标签 python beautifulsoup

html代码是这样的:

<div class="AAA">Text of AAA<a href="......AAA/url">Display text of URL A</a></div>
<div class="BBB">Text of BBB<a href="......BBB/url">Display text of URL B</a></div>
<div class="CCC">Text of CCC</div>
<div class="DDD">Text of DDD</div>

我想解析所有div的文本,同时检查是否存在url,如果存在则将其提取出来并显示在输出中

输出如下:

Text of AAA
Display text of URL A
......AAA/url
Text of BBB
Display text of URL B
......BBB/url
Text of CCC
Text of DDD

我试图将 find_all('a') 的循环嵌套在 find_all('div') 循环中,但弄乱了我的输出

最佳答案

from bs4 import BeautifulSoup
html="""
<div class="AAA">Text of AAA<a href="......AAA/url">Display text of URL A</a></div>
<div class="BBB">Text of BBB<a href="......BBB/url">Display text of URL B</a></div>
<div class="CCC">Text of CCC</div>
<div class="DDD">Text of DDD</div>
"""
soup = BeautifulSoup(html, "lxml")
for div in soup.findAll('div'):
    print(div.text)
    try:
        print(div.find('a').text)
        print(div.find('a')["href"])
    except AttributeError:
        pass

输出

Text of AAADisplay text of URL A
Display text of URL A
......AAA/url
Text of BBBDisplay text of URL B
Display text of URL B
......BBB/url
Text of CCC
Text of DDD

关于python - 如何检查 <a href> 元素是否存在于 <div> 元素中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53904852/

相关文章:

python - 在 Python 中使用 BeautifulSoup 从 HTML 中删除回车符

Python3 beautifulsoup模块 'NoneType'错误

python - PyTest 跳过 module_teardown()

python - 使用 tac 文件与 twistd 一起运行时出现高速公路 websocket 问题

python - 如何使用 Selenium RC 保存和恢复所有 cookie?

python - 使用 Python 和 BeautifulSoup 获取字符串中 1-10 的正则表达式时出现问题

python - 使用漂亮的汤基于类和 href 标签解析 html 标签

python - Beautifulsoup - 在 soup.find() 中传递变量

python - 我的 numpy 数组显示以 "AttributeError: ' FloatFormat' 对象没有属性 'format' 结尾的长错误消息

python - OpenCV Python 中点的 warpPerspective 逆变换