仅使用Python请求刷新元素

时间:2016-12-09 15:25:33

标签: python python-requests lxml

我有一个脚本,使用python中的requests模块在网站上记录span字段。

from lxml import html
import requests

r = requests.get(url)
tree = html.fromstring(r.content)
while 1:
     print str(tree.xpath('//span[@id="ofr"]/text()')

然而,这个范围正在更新,我希望刷新它而不重新加载整个页面,为此我找不到解决方案。非常感谢

1 个答案:

答案 0 :(得分:0)

您需要在while 1中放置requests.get调用,否则不会向该网站发出新请求。 _lastValue保存上一轮的span值,脚本在每次查找之间休眠一秒钟。

from lxml import html
import time
import requests

_lastValue  = None
while 1:
    r = requests.get(url)
    tree = html.fromstring(r.content)
    _currentValue = str(tree.xpath('//span[@id="ofr"]/text()')

    if _currentValue != _lastValue:
        print _currentValue
        _lastValue = _currentValue

    time.sleep(1)