Skip to main content
 首页 » 编程设计

python之你如何从 BeautifulSoup 结果中获得第三个链接

2024年10月17日6zhengyun_ustc

我正在使用以下代码通过 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] 

请您参考如下方法:

首先,您应该停止使用 BeautifulSoup 版本 3 - 它已经很旧并且不再维护。切换到BeautifulSoup version 4 .通过以下方式安装:

pip install beautifulsoup4 

并将您的导入更改为:

from bs4 import BeautifulSoup 

然后,您需要使用find_all() 并通过索引递归获取第3 个链接,直到页面上没有第3 个链接。这是一种方法:

import urllib 
from bs4 import BeautifulSoup 
 
url = raw_input('Enter - ') 
 
while True: 
    html = urllib.urlopen(url) 
    soup = BeautifulSoup(html, "html.parser") 
 
    try: 
        url = soup.find_all('a')[2]["href"] 
        # if the link is not absolute, you might need `urljoin()` here 
    except IndexError: 
        break  # could not get the 3rd link - exiting the loop