Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python监视网站的更改_Python_Html_Web_Screen Scraping - Fatal编程技术网

Python监视网站的更改

Python监视网站的更改,python,html,web,screen-scraping,Python,Html,Web,Screen Scraping,我想登录到一个网站,获取数据,将其保存到一个文件中,一段时间后获取新数据,并将其与旧(保存的)数据进行比较,如果有更改,则打印。我该怎么做?登录正常,但比较无效。为什么? 提前谢谢你 我的代码: # -*- coding: utf-8 -*- import urllib import urllib2 import cookielib import time def login(): username = "username" password = "password"

我想登录到一个网站,获取数据,将其保存到一个文件中,一段时间后获取新数据,并将其与旧(保存的)数据进行比较,如果有更改,则打印。我该怎么做?登录正常,但比较无效。为什么?

提前谢谢你

我的代码:

# -*- coding: utf-8 -*-
import urllib
import urllib2
import cookielib
import time


def login():
    username = "username"
    password = "password"

    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    login_data = urllib.urlencode({'login_username' : username, 'login_password' : password})
    opener.open('lol.com/login', login_data)
    resp = opener.open('lol.com/login')
    data = resp.read()
    print data    
    write_data(data)

def write_data(data):
    file = open("htmlString", "w")
    file.write(data)
    file.close()
    monitor(data)



def monitor(data):
    string1 = open("htmlString", "r").read()
    string2 = data
    while True:
        time.sleep(5)
        login()
        if string1 == string2:
            print "Nothing has changed"
        else:
            print "Something has changed"




login()

我发现你的代码很难理解。这里有一个未经测试的替代方案,应该接近你想要实现的目标

def fetch_html():
    # fetch logic
    return html  # string

def write_html(html):  # string
    # write logic

def read_html():
    with open('page.html','r') as f:
        return f.read()

def monitor():
    write_html(fetch_html())
    while True:
        time.sleep(5)
        new_html = fetch_html()
        if new_html == read_html():
            print('Nothing has changed')
        else:
            print('Something has changed')
            write_html(new_html)

monitor()

问题是调用
login()
时,
string2
没有更新。您应该使
login()
返回
数据
,并将其分配给
string2
每个循环。

那么,到底是什么不起作用呢<代码>监视器,充其量(我不知道你的代码是否走得那么远),只能用于检测一个更改。在那之后,它就没有什么新的东西可以比较了,因为数据是固定的,它甚至没有打印“什么都没有改变”。这是一个问题。第二个问题是,正如你所说,它只比较了一次。我怎样才能解决这个问题?我真的不知道..嗯,那些
打印
是在
if
/
else
中出现的,所以你的代码没有那么远。您需要在流程中更早地进行调试。如果有错误,你应该把它放在你的问题里。你有打印出来的吗?