Python中的网络抓取-如何捕获所有<a> elements

时间:2018-10-10 00:14:03

标签: python web-scraping beautifulsoup

I'm using beautifulsoup4 to scrape data from the lyrics.com website, specifically this link: https://www.lyrics.com/album/1447935

我要从这个块中提取两个<a>元素:

[<table class="tdata">
    <colgroup>
        <col style="width: 50px;"/>
        <col style="width: 430px;"/>
        <col style="width: 80px;"/>
        <col style="width: 80px;"/>
    </colgroup>
    <thead>
        <tr>
            <th>#</th>
            <th>Song</th>
            <th>Duration</th>
            <th> </th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="tal qx">1</td>
            <td class="tal qx">
                <strong>
                    <a href="/lyric/15183453/Make+You+Feel+My+Love">Make You Feel My Love</a>
                </strong>
            </td>
            <td class="tal qx">3:32</td>
            <td class="tal vam rt"> 
            </td></tr><tr><td class="tal qx">2</td>
            <td class="tal qx">
                <strong>
                    <a href="/lyric/15183454/Painting+Pictures">Painting Pictures</a>
                </strong>
            </td>
            <td class="tal qx">3:33</td>
            <td class="tal vam rt"> </td>
        </tr>
    </tbody>
</table>]

这是我的代码:

url = "http://www.lyrics.com" + album_url
page = r.get(url)
soup = bs(page.content, "html.parser")
songs = [a.get('href') for a in (table.find('a') for table in soup.findAll('table')) if a]

但是,它只返回第一个<a>

['/lyric/15183453/Make+You+Feel+My+Love']

怎么了?

编辑:谢谢大家的回答!我赞成,但没有足够的代表来显示

4 个答案:

答案 0 :(得分:1)

能够使其适用于:

for a in soup.findAll('a'):
    if a.parent.name == 'strong':
        if a.parent.parent.name == 'td':
            print(a["href"])

但是仍然不确定为什么其他方法不起作用,因为我已经在程序的其他地方使用了它,没有问题。

答案 1 :(得分:1)

这将起作用:

songs = [song['href'] for song in soup.select('table a')]

输出:

['/lyric/15183453/Make+You+Feel+My+Love', '/lyric/15183454/Painting+Pictures']

答案 2 :(得分:1)

其他解决方案效果很好,但是我更喜欢使用旧的选择器

from bs4 import BeautifulSoup as bs
import requests as req
page = req.get('https://www.lyrics.com/album/1447935')
soup = bs(page.content, 'html.parser')
links = soup.select('table.tdata a[href]')
print(links)

这将打印

[<a href="/lyric/15183453/Make+You+Feel+My+Love">Make You Feel My Love</a>, <a href="/lyric/15183454/Painting+Pictures">Painting Pictures</a>]

如果您不熟悉选择器,它将获取具有类table的{​​{1}}个元素,然后收集tdata元素上的所有href属性< / p>

答案 3 :(得分:0)

好像您想要table.findAll而不是table.find