使用beautifulsoup Python获取div中的第一个链接

问题描述 投票:2回答:2

我正在尝试使用此HTML中的beautifulsoup获取此链接:

    <div id="downloads" style="text-align:left">
        Download as Excel tables:  
<a href="crispor.py?batchId=Kn3CuFPN9QbwruIqkBGk&download=guides&format=xls">Guides</a>

    <a href="crispor.py?batchId=Kn3CuFPN9QbwruIqkBGk&satMut=1">Saturating mutagenesis assistant</a><br>
            <small>Tab-sep format:  
    <a href="crispor.py?batchId=Kn3CuFPN9QbwruIqkBGk&download=guides&format=tsv">Guides</a>

我试过这段代码:

for link in soup.find_all('a', href=True, text='Guides'):
             crisporDL = link['href']

但这是输出上面的第二个链接,因为你可以看到两个都有文本'指南',我如何得到第一个链接?因为第一个链接返回一个XLS文件,而第二个链接返回一个TSV文件,我需要xls文件。

谢谢。

python html web-scraping hyperlink beautifulsoup
2个回答
1
投票

使用id选择器和a标签选择器传递给select_oneselect_one返回第一场比赛。它应该比使用find更快。

soup.select_one("#downloads a")['href']

0
投票

我认为你要找的是find()方法,它只返回第一场比赛。

crisporDL=soup.find('a', href=True, text='Guides')['href']

在这种情况下,您不需要使用for循环。

另一种可能没有对代码进行太多更改的可能性是将limit argument添加到find_all()。

soup.find_all('a', href=True, text='Guides',limit=1)

虽然这里完全没有必要,但是有些情况下你可能想要获得前n个匹配。

© www.soinside.com 2019 - 2024. All rights reserved.