在元素

时间:2017-12-01 00:44:09

标签: python-3.x beautifulsoup

所以,我想用美丽的汤来刮掉这个网站的专辑和歌曲。 HTML看起来像这样:

<div id="listAlbum"> 
    <a id="19215"></a>
    <div class="album">
    "album: "
    <b>"3 Feet High And Rising"</b> == $0
    " (1989)"
  </div> 
  <a href="https://www.azlyrics.com/lyrics/delasoul/intro.html" target="_blank">Intro
  </a>
  <br> 
  <a href="https://www.azlyrics.com/lyrics/delasoul/themagicnumber.html" target="_blank">The Magic Number</a>
  <br> 
  <a href="https://www.azlyrics.com/lyrics/delasoul/changeinspeak.html" target="_blank">Change In Speak</a>
  <br> 

我想提取这个:     专辑:3英尺高和上升     歌曲:简介,魔术数字,改变说话

我收到了这张专辑:

allAlbums = soup.findAll('div', {"class" : "album"})
for a in allAlbums:
    albumName = str(a.text)[7:]
    print('album: ' + str(a))

我无法弄清楚如何获取歌曲。我试过这些:

for s in soup(text = re.compile(r'target="_blank">')):
    print(s.parent)

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

试试这个。我希望它能获取所需的输出:

from bs4 import BeautifulSoup

html_content='''
  <div id="listAlbum">
   <a id="19215">
   </a>
   <div class="album">
    "album: "
    <b>
     "3 Feet High And Rising"
    </b>
    == $0
    " (1989)"
   </div>
   <a href="https://www.azlyrics.com/lyrics/delasoul/intro.html" target="_blank">
    Intro
   </a>
   <br/>
   <a href="https://www.azlyrics.com/lyrics/delasoul/themagicnumber.html" target="_blank">
    The Magic Number
   </a>
   <br/>
   <a href="https://www.azlyrics.com/lyrics/delasoul/changeinspeak.html" target="_blank">
    Change In Speak
   </a>
   <br/>
  </div>
'''
soup = BeautifulSoup(html_content,"lxml")
for item in soup.select("#listAlbum .album,#listAlbum a"):
    print(item.text.strip())

它产生了什么:

"album: "
"3 Feet High And Rising"   
== $0
" (1989)"

Intro
The Magic Number
Change In Speak

答案 1 :(得分:0)

这是另一种方法:

## Prints every album
albums = soup.find_all(class_="album")
for album in albums:
    print(album.get_text())

## Prints every song
songs = soup.find_all('a', target="_blank")
for song in songs:
    print(song.get_text())