【问题标题】:Difference between 2 list2个列表之间的区别
【发布时间】:2018-09-30 19:24:06
【问题描述】:

在输出不在第二个列表中的列表中的项目时,我遇到了以下问题。

代码如下:

def getInitialList(): # Define initial list with the use of requests and BS, will return a set

    getInHtml = requests.get("http://127.0.0.1")
    parseInHtml = BeautifulSoup(getInHtml.content, "html.parser")

    processInHtml = parseInHtml.find_all("div", class_="inner-article")

    firstList = []

    for items in processInHtml:
        firstList.append(items)

    return firstList

def getSecList(): #Define second list with the use of requests and BS, will return a set
    getHtml = requests.get("http://127.0.0.1")
    parseHtml = BeautifulSoup(getHtml.content, "html.parser")

    processHtml = parseHtml.find_all("div", class_="inner-article")

    secList = []

    for items in processHtml:
        secList.append(items)

    return secList

def catch_new_item():

    initList = getInitialList()

    while True:
        if initList == getSecList():
            print("No new items")
        else:
            print("New items found")
            break
    secList = getSecList()
    return set(secList) - set(initList)

最后一个函数 (catch_new_items()) 应该返回 secList 中的内容,而不是 initList 中的内容,但是当我运行它时,它返回一个空集。

地址 127.0.0.1 它是一个本地 Web 服务器,我正在运行以确定这两个项目之间的差异。我所做的就是编辑 html 并向其中添加一个元素。

让我知道你的想法?

【问题讨论】:

    标签: python python-3.x beautifulsoup python-requests python-3.6


    【解决方案1】:

    我以这种方式修改了代码,以进行调试:

    def getInitialList(): # Define initial list with the use of requests and BS, will return a set
    
        firstList = ['1', '2', '3']
        return firstList
    
    def getSecList(): #Define second list with the use of requests and BS, will return a set
    
        secList = ['a', 'b', '3', '1']
        return secList
    
    def catch_new_item():
    
        initList = getInitialList()
        while True:
            if initList == getSecList():
                print("No new items")
            else:
                print("New items found")
            break
        secList = getSecList()
        return set(secList) - set(initList)
    
    print(catch_new_item())
    

    然后它返回:

    New items found
    {'a'}
    

    所以物品检测的逻辑是好的。

    1. 您是否尝试从 getInitialList() 中打印出您的列表和 getSecList() 函数看看,是否为空?
    2. 列表真的包含不同的项目吗? (如果它们不为空,请参阅 页。 1)

    【讨论】:

    • 此列表解析相同的 html 页面,不同之处在于 secondList 将继续获取 html 元素,直到找到 1 个或更多差异,然后 catch 函数应输出 secList 中的项目而不是在初始化列表中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    相关资源
    最近更新 更多