简体   繁体   English

使用 selenium python 从 span 中的句子中获取最后一个元素

[英]get last element from a sentence in span using selenium python

I want to scrape last word of a sentence defined in a span using selenium python.我想使用 selenium python 抓取跨度中定义的句子的最后一个单词。 I am able to get the whole sentence using this:-我可以用这个得到整个句子:-

elements = browser.find_element_by_css_selector("span[ng-if='!product.product.isOnlyCarCategory']");
print elements
result = elements.text
print result

Output:- Buy for Rs 329输出:- Buy for Rs 329

I want only 329 to be output not the whole sentence.我只想输出 329 而不是整个句子。 I've tried using replace function of python and able to achieve what I want like this:-我试过使用 python 的替换功能,并且能够像这样实现我想要的:-

elements = browser.find_element_by_css_selector("span[ng-if='!product.product.isOnlyCarCategory']");
print elements
result = elements.text
result = int(result.replace('Buy for Rs ',''))
print result

Output:- 329输出:- 329

but I don't want to use replace function.但我不想使用替换功能。 I want to use selenium to do the same.我想用硒来做同样的事情。 And yes this integer value is dynamic是的,这个整数值是动态的

Is there any way to do that?有没有办法做到这一点?

You can use a regex, or a for loop instead:您可以改用正则表达式或 for 循环:

strNum = ""
for c in result[::-1]:
    if c.isdigit():
        strNum=c+strNum
    elif len(strNum)>0:
        break
num=into(strNum)
print num

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

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