我正在使用以下代码来使用BeautifulSoup检索一堆链接。它会返回所有链接,但我想获得第三个链接,解析该链接,然后获取第三个链接,依此类推。我怎样才能修改下面的代码来完成呢?如何从BeautifulSoup结果获得第三个链接
import urllib
from BeautifulSoup import *
url = raw_input('Enter - ')
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
# Retrieve all of the anchor tags
tags = soup('a')
for tag in tags:
print tag.get('href', None)
print tag.contents[0]
谢谢您回复alecxe。在上面的代码中,“tags = soup('a')返回一个列表,然后当执行”print“时,我得到很多链接,所以它似乎给我所有链接而不使用”find_all“。这就是为什么我不能'简单地打印标签[2],我认为这是循环迭代的第3个链接。 – martinbshp
@martinbshp是的,'soup()'是'soup.find_all()'的快捷方式。是的,你需要得到'href'属性值,如答案中所示: – alecxe
哦,我现在明白了,你的回应促使我回去重新考虑这件事,看看标签是我需要询问的索引而不是for循环中的变量var。谢谢。 – martinbshp