使用BeautifulSoup获取跨度之间的文本

时间:2018-10-03 22:42:33

标签: python beautifulsoup lxml

我正在尝试使用Python中的BeautifulSoup抓取各种站点。说我有以下html摘录:

<div class="member_biography">
<h3>Biography</h3>
<span class="sub_heading">District:</span> AnyState - At Large<br/>
<span class="sub_heading">Political Highlights:</span> AnyTown City Council, 19XX-XX<br/>
<span class="sub_heading">Born:</span> June X, 19XX; AnyTown, Calif.<br/>
<span class="sub_heading">Residence:</span> Some Town<br/>
<span class="sub_heading">Religion:</span> Episcopalian<br/>
<span class="sub_heading">Family:</span> Wife, Some Name; two children<br/>
<span class="sub_heading">Education:</span> Some State College, A.A. 19XX; Some Other State College, B.A. 19XX<br/>
<span class="sub_heading">Elected:</span> 19XX<br/>
</div>

我需要结果采用以下格式:

District:              AnyState - At Large
Political Highlights:  AnyTown City Council, 19XX-XX
Born:                  June X, 19XX; AnyTown, Calif.
Residence:             Some Town
Religion:              Episcopalian
Family:                Wife, Some Name; two children
Education:             Some State College, A.A. 19XX; Some Other State College, B.A. 19XX
Elected:               19XX

但是,到目前为止,我只能实现以下目标:

District:
Political Highlights:
Born:
Residence:
Religion:
Family:
Education:
Elected:

使用以下代码:

import urllib.request
import sys
from bs4 import BeautifulSoup

def main(url):
    fp = urllib.request.urlopen(url)
    site_bytearray = fp.read()
    fp.close()

    #bs_data = BeautifulSoup(site_str,features="html.parser")
    bs_data = BeautifulSoup(site_bytearray,'lxml')
    tmplist = bs_data.find_all('span',{'class':'sub_heading'})
    for item in tmplist:
        print(item.text)
    sys.exit(0)

if __name__ == "__main__":
    main(sys.argv[1])

简而言之,如何从District中提取AnyState - At Large<span class="sub_heading">District:</span> AnyState - At Large<br/>并将结果累积在列表中以进行进一步处理?

2 个答案:

答案 0 :(得分:5)

将打印命令替换为:

Python 3.6 +:

print(f'{item.text:<25} {item.next_sibling}') 

Python 3-3.5:

print('{:<25} {}'.format(item.text, item.next_sibling))

输出:

District:                  AnyState - At Large
Political Highlights:      AnyTown City Council, 19XX-XX
Born:                      June X, 19XX; AnyTown, Calif.
Residence:                 Some Town
Religion:                  Episcopalian
Family:                    Wife, Some Name; two children
Education:                 Some State College, A.A. 19XX; Some Other State College, B.A. 19XX
Elected:                   19XX

答案 1 :(得分:0)

您尝试过使用getText()似乎总是对我有用。