代码之家  ›  专栏  ›  技术社区  ›  Chevady Ju

在Python中尝试pop异常

  •  0
  • Chevady Ju  · 技术社区  · 7 年前

    t1.py主程序

    t3.py子程序

    不一定,但有时在主程序中可能会遇到下面的错误 有什么解决办法吗?

    ------错误消息--------

    res=list_links.pop(random.randint(1,len(list_links)))#根据列表大小随机弹出每个项目

    索引器错误:弹出索引超出范围


    # -*- coding: utf-8 -*-
    """
    Created on Fri Oct  5 21:51:34 2018
    
    @author: chevady
    """
    from linebot.models import *
    from t3 import apple_newsss
    apple_newss_content0, apple_newss_content1, apple_newss_content2 = apple_newsss()
    
    print(apple_newss_content0)
    
    print(apple_newss_content1)
    
    print(apple_newss_content2)
    

    t3.py型

    # -*- coding: utf-8 -*-
    import requests
    import re
    import os
    import random
    from bs4 import BeautifulSoup
    from flask import Flask, request, abort
    #from imgurpython import ImgurClient
    from argparse import ArgumentParser
    
    def apple_newsss():
    
        target_url = 'http://www.appledaily.com.tw/realtimenews/section/new/'
        print('Start parsing appleNews....')
        rs = requests.session()
        res = rs.get(target_url, verify=False)
        soup = BeautifulSoup(res.text, 'html.parser')
    
        list_links = [] # Create empty list
    
        for a in soup.select("div[class='abdominis rlby clearmen']")[0].findAll(href=True): # find links based on div
                if a['href']!= None and a['href'].startswith('https://'):
                        list_links.append(a['href']) #append to the list
                        print(a['href']) #Check links
    
    #for l in list_links: # print list to screen (2nd check)
    #    print(l)
    
    
        print("\n")
    
        random_list = [] #create random list if needed..
        random.shuffle(list_links) #random shuffle the list
        apple_newss_content0 = ''
        apple_newss_content1 = ''
        apple_newss_content2 = ''
        for i in range(3): # specify range (5 items in this instance)
            res = list_links.pop(random.randint(1, len(list_links))) # pop of each item randomly based on the size of the list
            random_list.append(res)
        #print(res)
        #print(random_list)
        print("\n")
        apple_newss_content0=random_list[0]
        apple_newss_content1=random_list[1]
        apple_newss_content2=random_list[2]
    
        print(apple_newss_content0)
        print(apple_newss_content1)
        print(apple_newss_content2)
    
        return apple_newss_content0, apple_newss_content1, apple_newss_content2
    

    谢谢!!!

    2 回复  |  直到 7 年前
        1
  •  2
  •   Rakesh    7 年前

    使用 len(list_links)-1

    前任:

    for i in range(3): # specify range (5 items in this instance)
        res = list_links.pop(random.randint(1, len(list_links)-1)) # pop of each item randomly based on the size of the list
        random_list.append(res)
    
        2
  •  1
  •   bruno desthuilliers    7 年前

    res = list_links.pop(random.randint(1, len(list_links)))
    

    表达式 random.randint(1, len(list_links)) len(list_links) ,但是(像大多数其他语言FWIW一样)python列表索引是基于零的,所以您需要 random.randint(0, len(list_links) - 1)

    list_links 其中至少有3个项,因此如果它是空的或在for循环期间变为空,则仍然会得到一个错误。

    编辑

    而且,您的代码比需要的复杂得多。如果你想要的是3个随机不同的网址 列出\u链接

    # make sure we only have distinct urls
    list_links = list(set(list_links))
    # make sure the urls are in arbitrary order
    random.shuffle(list_links) 
    # returns the x (x <= 3) first urls 
    return list_links[:3]
    

    min(3, len(linked_lists) 实际上是URL,所以调用者不应该总是依赖于3个URL的返回,但这并不是必须的:每次你发现自己在写东西的时候 somevar1, somevar2, somevarN

    urls = apple_newsss()
    for url in urls:
        print(url)