我正在尝试监控页面是否有任何更新。但是,我需要保持相同的会话和cookie,所以我不能只发送一个新的请求。
如何在当前请求中检查HTML中的更新?页面不会只是更新,我将被重定向,但URL保持不变。
这是我目前的代码:
import requests
url = 'xxx'
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
}
response = requests.get(url, headers=headers, allow_redirects=True, config={'keep_alive': True})
def get_status():
html = response.text # this should be the current HTML, not the HTML when I made the initial request
if x in html:
status = "exists"
else:
status = "null"
return status
print(get_status())
编辑:我将使用while循环每隔5秒运行一次此函数,以检查状态是否为“存在”。
EDIT2:我试图通过requests_html实现它,但我没有得到尽可能多的cookie:
import requests_html
from requests_html import HTMLSession
session = HTMLSession()
session.headers.update({'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'})
r = session.get('x')
r.html.render(reload=False)
print(r.cookies.get_dict())
答案 0 :(得分:0)
但是,我需要保留相同的会话和Cookie,以便我无法发送全新的请求。
您要在此处执行的操作是使用
打开会话s = requests.Session()
response = s.get("http://www.google.com")
这将确保在请求中保留cookie和某些其他内容。导航至the documentation of Sessions以获取更多详细信息。
由于您只是想检查返回的html是否与上一个请求完全相同,只需将第一个response.text
保存在您的函数之外,然后检查您的新response.text
是否等于保存的那个found &= pattern[j] == *(char*)(base + i + j);
早。
如果网站动态显示任何内容,这当然不会起作用,但如果您可以检查DOM中的特定元素并将其与上一个请求中的对象进行比较,那么这将正常工作。