如何发出python请求。请稍等几秒钟?

2024-05-16 21:00:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想获得一些html爬行的经验,所以我想看看是否可以获取以下站点的一些值:http://www.iex.nl/Aandeel-Koers/11890/Royal-Imtech/koers.aspx

这个网站显示了imtech股票的价格。 如果你看一下这个网站,你会发现有1个数字用粗体显示,这是股票的价格。

你可能已经看到了,这个价格变了,没关系。我只需要在这个时间点运行脚本时的值。

但如果重新加载页面,您可能会注意到它首先显示“laatste koers”,延迟1秒后显示“realtime”

你现在可能已经知道了,我对“实时”价值感兴趣。

这是我的问题,我怎么得到这个值,我试过时间。在不同的地方睡觉。我已经按要求暂停了。两个都没用。

我该怎么解决?

from lxml import html
import requests

pagina = 'http://www.iex.nl/Aandeel-Koers/11890/Royal-Imtech/koers.aspx'

page = requests.get(pagina)
tree = html.fromstring(page.text)

koers = tree.xpath('//span[@class="RealtimeLabel"]/text()')

prices = tree.xpath('//span[@id="ctl00_ctl00_Content_LeftContent_PriceDetails_lblLastPrice"]/text()')
print koers[0], pagina.split("/")[5], prices[0]

我得到这样的输出

Laatste koers Royal-Imtech 0,093

我想要这样的输出

Realtime Royal-Imtech 0,093

Tags: texttreehttphtmlwwwnl价格iex
1条回答
网友
1楼 · 发布于 2024-05-16 21:00:56

我建议使用一个等待,直到元素改变。

找到下面的代码块来帮助您。

def wait_while(condition, timeout, delta=1):
    """
    @condition: lambda function which checks if the text contains "REALTIME"
    @timeout: Max waiting time
    @delta: time after which another check has to be made
    """
    max_time = time.time() + timeout
    while max_time > time.time():
        if condition():
            return True
        time.sleep(delta)
    return False

相关问题 更多 >