【问题标题】:how to make a recursive loop in python如何在python中进行递归循环
【发布时间】:2014-12-28 19:41:18
【问题描述】:

我正在尝试制作一个可以使用 BeautifulSoup 循环浏览页面的网络爬虫

为此,我正在尝试编写一个函数来调用我正在寻找的页面,找到下一个按钮的 Href 打印结果,然后将其分配给请求并重复该函数以递归方式打印每个下一个按钮的新值。

这就是我所拥有的,但我无法真正弄清楚它不起作用。我没有收到任何错误,所以我认为我的结构可能已经关闭。

提前谢谢你。

import urllib.request
from bs4 import BeautifulSoup
import re

url = "http://www.calaiswine.co.uk/products/type/all-wines/1.aspx"
root_url = "http://www.calaiswine.co.uk"
first_index_url =  '/products/type/all-wines/1.aspx'

htmlFile = urllib.request.urlopen(url);

htmlText = htmlFile.read();

soup = BeautifulSoup(htmlText);

def cycle_to_next_page(foo):
    response = urllib.request.urlopen( root_url + foo)
    soup = BeautifulSoup(response)
    items = [a.attrs.get('href') for a in soup.findAll('a', title='Next')]
    print (cycle_to_next_page(items[0]))

cycle_to_next_page(first_index_url)

【问题讨论】:

  • 你的递归循环是如何终止的?
  • 你想用什么语言写作?您的代码中不应有任何 ;

标签: python recursion request web-scraping beautifulsoup


【解决方案1】:

您的递归函数不返回任何内容,它只是打印。

在 Python 中,不返回的函数被视为返回 None。所以,Python 理解你的cycle_to_next_page(first_index_url) 指令就像你理解了:

print(print(None))

我个人不会在这个例子中使用递归。只是一个基本的for 循环遍历items

【讨论】:

    【解决方案2】:

    删除你的print,就像@Jivan 解释的那样实际递归调用函数,你也不需要重复第一个`urllib.urlopen'调用,你也可以用相同的函数打开初始页面。像这样的:

    import urllib
    from bs4 import BeautifulSoup
    
    root_url = "http://www.calaiswine.co.uk"
    first_index_url =  '/products/type/all-wines/1.aspx'
    
    
    def cycle_to_next_page(link):
        response = urllib.urlopen(root_url+link)
        soup = BeautifulSoup(response.read())
        # my bs4 use find_all instead
        items = [a.attrs.get('href') for a in soup.find_all('a', title="Next")]
        print items[0]
        if items[0]:
            # here is the recursive function call, do a proper return, not print
            return cycle_to_next_page(items[0])
        print "crawling completed"
        return
    
    # you can open your initial page with this function too
    cycle_to_next_page(first_index_url)
    
    #results:
    /products/type/all-wines/2.aspx
    /products/type/all-wines/3.aspx
    /products/type/all-wines/4.aspx
    ...
    

    另外,不确定您是否只想要items[0] 或所有项目,无论如何您可以更改逻辑并相应地调用函数。 希望这可以帮助。

    【讨论】:

      猜你喜欢
      • 2016-07-18
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 2017-09-27
      • 2015-12-30
      • 2021-02-08
      • 1970-01-01
      相关资源
      最近更新 更多