python - 使用 BeautifulSoup 提取 <Div class> 标记之间存在的值

标签 python beautifulsoup

在下面的 HTML 代码中,我需要提取“txtDetail”类中存在的字符串“PMR/SMR Effectness”。但在我的代码中,它正在获取所有文本元素。我在 stackoverflow 上看到过很多这样的例子,但对我来说没有任何作用。请让我知道我的代码出了什么问题。

soup = BeautifulSoup(driver.page_source,'html.parser')
for i in soup.find_all(class_ ='default yellowBorder Hclass ' ):
    if soup.find_all('div',attrs={"class" : "txtDetail"}):
        print(i.text)

预期输出:PMR/SMR 有效性

实际输出: HPPMR/SMR 有效性 PMR/SMR 有效性 PMR/SMR 有效性计算公式 PMR/SMR 按照建议频率进行/审核

HTML 代码:

<ul class="blockList" id="ulexceptionlist"><li class="default yellowBorder Hclass "><div class="blockCont"> <div class="yellowBlock dispBlock expPoints"><div class="iconException">H</div><div class="yellowSection">P</div></div><div class=" nextCont  textCont activeCont " onclick="loadMerticchart(this,&quot;drill1&quot;,&quot; AND m.MetricId=20&quot;,&quot;2&quot;,&quot;PMR/SMR Effectiveness&quot;,&quot;20&quot;,&quot;286&quot;,&quot;0&quot;,&quot;0&quot;)" descopereason=""><div class="txtDetail">PMR/SMR Effectiveness</div></div><div class="infoIcon " id="info1" data-hasqtip="4"></div><div class="col-xs-12 noPadding popupContainer"> <div class="col-md-12 dropdownContent pull-left"> <span class="clearfix"></span> <span class="pull-left content"><h6 class="tooltipTitle"> PMR/SMR Effectiveness </h6> <span class="tooltipCont"> PMR/SMR Effectiveness </span><br><br><h6 class="tooltipTitle"> Computation Formula </h6> <span class="tooltipCont"> PMR/SMR  is conducted/reviewed as per recommended frequency </span></span> </div></div></div></li>

最佳答案

因为您在 i 变量(即 li 标记)上调用 .text 。我稍微修改了你的代码:

for i in soup.find_all(class_ ='default yellowBorder Hclass ' ):
    divs = soup.find_all('div',attrs={"class" : "txtDetail"})
    for d in divs:
        print(d.text)

关于python - 使用 BeautifulSoup 提取 <Div class> 标记之间存在的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47158548/

相关文章:

python - imread在Spyder中有效,但在VS Code中无效

python - BeautifulSoup 迭代不起作用

python : how to get the text in <li> using BeautifulSoup

python - 仅当有两个类并且共享相同的第一个时才选择元素

python-3.x - 我如何使用 beautifulsoup 从维基百科表中提取一条数据

python - 无法使用 BS4 从 <a> 标签中提取 href 值

Python格式化Ctime方法

python - 计算任意(非二叉)树的高度

python - 使用蒙特卡洛方法绘制 Pi

Python for 循环范围内的增强算术