如何提取特定段落标记

2024-10-01 04:54:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想摘录这个回复的内容:

<div class="bio-container">
   <p class="bio profile" >
       Chinedu is a good boy
   </p>
</div>

请假设还有其他paragrpah标记具有不同的类属性,但我想用class属性“bio profile”提取这个标签

我只是想提取一个好文件。在

我试过desc = bs.find ('p', {'class' : 'bio profile'})

但不起作用

我正试图将上述答案应用于:

^{pr2}$

但我得到了一个错误陈述

print desc.get_text().strip()
AttributeError: 'NoneType' object has no attribute 'get_text'

Tags: textdiv内容get属性iscontainerprofile
3条回答

使用BeautifulGroup模块从<p>标记提取所有文本。在

内容脚本.py:

from bs4 import BeautifulSoup
import sys 

soup = BeautifulSoup(open(sys.argv[1], 'r'), 'html')

    print(' '.join(map(lambda e: e.string, soup.find_all('p'))))

运行方式如下:

^{pr2}$

试试这个

from BeautifulSoup import BeautifulSoup as bs
soup = bs(<Your html>)
soup.p.text

您应该对desc使用.get_text()方法。使用Python 2.7和BS 4.3.2:

from bs4 import BeautifulSoup as bsoup

ofile = open("test.html")
soup = bsoup(ofile)

desc = soup.find("p", class_="bio profile")
# or desc = soup.find("p", {"class":"bio profile"})
print desc.get_text().strip()

结果:

^{pr2}$

希望这有帮助。在

相关问题 更多 >