我正在尝试使用此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文件。
谢谢。
使用id选择器和a
标签选择器传递给select_one
。 select_one
返回第一场比赛。它应该比使用find更快。
soup.select_one("#downloads a")['href']
我认为你要找的是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个匹配。