繁体   English   中英

为什么这适用于此,但不适用于此? [硒] [Python]

[英]Why does this work on this, but not on this? [Selenium] [Python]

我正在做一个库存检查器,当我在 Finance.yahoo.com 中的go到 Amazon (AMZN) 时遇到了一些问题。 我的代码运行良好,但是当我尝试例如 Tesla (TSLA) 时它不起作用。 这是我的代码的一部分。

getperstock = driver.find_element_by_xpath('//*[@class="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"]').text #Works
print(str(getperstock))
#"Trsdu(0.3s) Fw(500) Pstart(10px) Fz(24px) C($negativeColor)"
getstockratio = driver.find_element_by_xpath('//*[@class="Trsdu(0.3s) Fw(500) Pstart(10px) Fz(24px) C($positiveColor)"]').text #Doesnt
print(str(getstockratio))

这是最小的 HTML

<div class="D(ib) Mend(20px)" data-reactid="31">
    <span class="Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"
        data-reactid="32">670.97</span>
    <span class="Trsdu(0.3s) Fw(500) Pstart(10px) Fz(24px) C($negativeColor)"
        data-reactid="33">-20.65 (-2.99%)</span>
    <div id="quote-market-notice" class="C($tertiaryColor) D(b) Fz(12px) Fw(n) Mstart(0)--mobpsm Mt(6px)--mobpsm"
        data-reactid="34">
        <span data-reactid="35">At close: 4:00PM EDT</span>
    </div>
</div>

您的第一个 xpath 获得第一个span是可以的。 但是第二个span将包括negativepositive ,因此如果股票是负数/正数,它将无法找到该元素。 我在您的评论中看到您说它有效,但我敢肯定,一旦相反,它就会失败。

更好的方法:

# get parent of both `span`
parent = driver.find_element_by_xpath('//div[@class="D(ib) Mend(20px)"]')
# get the `span` insides
span_elems = parent.find_elements_by_tag_name("span")

# first one is the stock price
price = span_elems[0].text
# second span is the %
ratio = span_elems[1].text
# third one is the "at close..." but you dont need it

顺便说一句,不要使用find_elements...来查找父节点。 使用显式等待将使代码有效地为您完成等待部分: https://selenium-python.readthedocs.io/waits.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM