【问题标题】:Are there better ways to approach these Python loops?有没有更好的方法来处理这些 Python 循环?
【发布时间】:2015-02-20 11:07:25
【问题描述】:

我正在处理一个抓取准备功能,其中结果页面导致产品页面。该函数有一个默认的最大结果页数,或每组结果的页数,以防止出现简单的错误。

这是我目前所拥有的。我用 for 循环实现最大值的方式有意义吗?有没有更“pythonic”的方式?我是从一个完全学习的角度来解决这个问题的。谢谢。

def my_crawler(url, max_pages = 1, max_items = 1):

    for page_number in range(1, max_pages + 1):
        url = url + str(page_number)
        source_code = requests.get(url).text

        products = SoupStrainer(class_ = 'productTags')
        soup = BeautifulSoup(source_code, 'html.parser', parse_only=products)

        for item_number, a in enumerate(soup.find_all('a')):
            print(str(item_number) + ': ' + a['href'])

            if item_number == max_items - 1: break

my_crawler('http://www.thesite.com/productResults.aspx?&No=')

【问题讨论】:

  • 您应该考虑在url 上使用字符串格式,而不是仅仅附加数字。
  • 你的问题更适合codereview.SE(考虑到你的代码确实有效)。

标签: python python-3.x


【解决方案1】:

for 循环很好,但是

def my_crawler(url, max_pages = 1, max_items = 1):
    for page_number in range(1, max_pages + 1):
        url = url + str(page_number)
         ^
         |

您已更改url 参数;下次循环时,这将无法正常工作(您将寻找第 1 页、第 12 页、第 123 页...)

试试吧

    source_code = requests.get(url + str(page_number)).text

这会在不更改url 的情况下生成一个临时字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 2020-01-08
    • 2014-06-29
    相关资源
    最近更新 更多