首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >美丽的汤:从<p>标签中提取细节

美丽的汤:从<p>标签中提取细节
EN

Stack Overflow用户
提问于 2017-07-12 15:59:43
回答 1查看 1.3K关注 0票数 0

我的HTML页面如下所示:

代码语言:javascript
复制
 data = <section class="otln" itemscope="" itemtype="http://microformats.org/wiki/hCard">
 <header>
 <h3 class="org">Website:</h3>
 </header>
 <p><a href="http://www.abilityone.gov">U.S. AbilityOne Commission </a></p> </section>,
 <section class="otln" itemscope="" itemtype="http://microformats.org/wiki/hCard">
 <header>
 <h3 itemprop="name">Main Address:</h3>
 </header>
 <p class="spk street-address">1401 S. Clark Street<br/>Suite 715<br/><span class="locality">Arlington</span>, <span class="region">VA</span> <span class="postal-code">22202-3259</span></p> </section>,
 <section class="otln" itemscope="" itemtype="http://microformats.org/wiki/hCard">
 <header>
 <h3 itemprop="name">Phone Number:</h3>
 </header>
 <p>1-703-603-7740</p> </section>,
 <section class="otln" itemscope="" itemtype="http://microformats.org/wiki/hCard">
 <header>
 <h3 class="org">Government branch:</h3>
 </header>
 <p>Executive Department Sub-Office/Agency/Bureau</p>
 </section>

我想从这个网页的<p>标签中提取所有细节,比如网站的href,主要地址,电话号码和政府部门。我尝试了许多不同的变化,以获得他们,但不能完全做到这一点。

编辑的

我的守则:

代码语言:javascript
复制
soup = BeautifulSoup(data,'lxml')
 website.append([l.find('a')['href'] for l in soup.find_all('section',class_='otln')])

以上尝试得到的'href‘抛出TypeError: 'NoneType' object is not subscriptable我有工作解决方案,以获得主要地址,电话号码,和政府部门。如果我能得到网站的'href‘,也就是"http://www.ability.gov“,会更好

EN

回答 1

Stack Overflow用户

发布于 2017-07-13 18:14:34

代码语言:javascript
复制
soup = BeautifulSoup(data, 'lxml')
for h, p in zip(soup.findAll('h3'), soup.findAll('p')):
    # h is the header, p is the paragraph
    a = p.find('a') # is it the website ?
    print('%-20s\t%s' % (h.text, a['href'] if bool(a) else p.text))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45062616

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档