Skip to main content
 首页 » 编程设计

Python 更新函数内的值并重用它

2024年10月24日10JustinYoung

我对此进行了很多搜索,但我可能使用了错误的术语,我找到的答案不是很相关,或者它们对我来说太先进了。

所以,我有一个非常简单的程序。我有一个读取网页的功能,使用 BeautifulSoup 扫描 href 链接,获取它找到的链接之一并跟随它。该函数通过用户输入获取第一个链接。

现在我希望这个函数使用它找到的链接自动重新运行,但我只能通过使用它获得的第一个变量来创建无限循环。这一切都是在一个最大深度为 10 个链接的受控环境中完成的。

这是我的代码:

import urllib 
from BeautifulSoup import * 
site=list() 
 
def follinks(x): 
    html = urllib.urlopen(x).read() 
    bs = BeautifulSoup(html) 
    tags = bs('a') 
    for tag in tags: 
        site.append(tag.get('href', None)) 
    x=site[2] 
    print x 
    return; 
url1 = raw_input('Enter url:') 

我如何让它使用 x 变量并返回开始并重新运行该函数,直到没有更多链接可以跟随?我尝试了 while true 的几种变体,但再次以用户提供的 url 的无限循环结束。

谢谢。

请您参考如下方法:

您正在寻找的是递归。这是您从其自己的主体定义中调用方法的地方。

def follow_links(x): 
    html = urllib.urlopen(x).read() 
    bs = BeautifulSoup(html) 
 
    # Put all the links on page x into the pagelinks list 
    pagelinks = [] 
    tags = bs('a') 
    for tag in tags: 
        pagelinks.append(tag.get('href', None)) 
 
    # Track all links from this page in the master sites list 
    site += pagelinks 
 
    # Follow the third link, if there is one 
    if len(pagelinks) > 2: 
        follow_links(pagelinks[2])