Python 递归函数完成后返回额外的'None'



我正在为一个学校项目编写一个web scraper,该项目对页面上找到的所有有效URL进行编目,并可以跟随URL进入下一个网页并执行相同的操作;直到设定数量的层。

快速代码意图:

  1. 函数采用BeautifulSoup类型、url(指示其开始位置)、层数和最大层深度
  2. 检查页面中的所有href行
  3. 每次找到包含有效url的href标记时,都会填充"结果"列表的append(以http、https、http、https开头;我知道这可能不是检查的完美方法,但目前我正在使用它)
  4. 每当找到有效的URL时,该层就会增加1—再次调用recursiveLinkSearch()函数
  5. 当达到层数,或者没有剩余href时,返回结果列表

我对递归非常不熟悉,并且遇到了python向列表中添加"None"的问题"结果";在递归结束时。

此链接[https://stackoverflow.com/questions/61691657/python-recursive-function-returns-none]指示它可能是我退出功能的位置。由于嵌套的for循环,我也不确定递归是否正常运行。

我们非常感谢您对递归退出策略的任何帮助或见解。

def curlURL(url):
# beautify with BS
soup = BeautifulSoup(requests.get(url, timeout=3).text, "html.parser")
return soup

def recursiveLinkSearch(soup, url, layer, depth):
results = []
# for each 'href' found on the page, check if it is a URL
for a in soup.find_all(href=True):
try:
# for every href found, check if contains http or https
if any(stringStartsWith in a.get('href')[0:4] for stringStartsWith in ["http", "https", "HTTP", "HTTPS"]) 
and a.get('href') != url and layer < depth:
print(f"Found URL: {a.get('href')}")
print(f"LOG: {colors.yellow}Current Layer: {layer}{colors.end}")
results.append(a.get('href'))
# BUG: adds an extra "None" type to the end of each list
results.append(recursiveLinkSearch(curlURL(a.get('href')), a.get('href'), layer+1, depth))
# Exceptions Stack
except requests.exceptions.InvalidSchema:
print(f"{a.get('href')}")
print(f"{colors.bad}Invalid Url Detected{colors.end}")
except requests.exceptions.ConnectTimeout:
print(f"{a.get('href')}")
print(f"{colors.bad}Connection Timeout. Passing...")
except requests.exceptions.SSLError:
print(f"{a.get('href')}")
print(f"{colors.bad}SSL Certificate Error.  Passing...")
except requests.exceptions.ReadTimeout:
print(f"{a.get('href')}")
print(f"{colors.bad}Read Timeout.  Passing...")
# exit recursion
if results != []:
print(f"LOG: {results[-1]}")
return results

这不是递归问题。最后,在if results != []:中,您打印了一些内容并返回results。否则,函数将结束,将不返回任何东西。但在python中,如果您附加了函数的值,但没有返回任何值,则会得到None。所以当你的结果为空时,你得到的是None

您可以检查您正在添加的内容,或者如果您在添加后得到None,则可以检查pop()

最新更新