In selenium, when I search Xpath how do I capture the element two positions before?

空扰寡人 提交于 2019-12-24 18:18:07

问题


In Python 3 and selenium I have this script to automate the search of terms in a site with public information

from selenium import webdriver

# Driver Path
CHROME = '/usr/bin/google-chrome'
CHROMEDRIVER = '/home/abraji/Documentos/Code/chromedriver_linux64/chromedriver'
# Chosen browser options
chrome_options = webdriver.chrome.options.Options()
chrome_options.add_argument('--window-size=1920,1080')
chrome_options.binary_location = CHROME

# Website accessed
link = 'https://pjd.tjgo.jus.br/BuscaProcessoPublica?PaginaAtual=2&Passo=7'

# Search term
nome = "MARCONI FERREIRA PERILLO JUNIOR"

# Waiting time
wait = 60 

# Open browser
browser = webdriver.Chrome(CHROMEDRIVER, options = chrome_options)
# Implicit wait
browser.implicitly_wait(wait)
# Access the link
browser.get(link)

# Search by term
browser.find_element_by_xpath("//*[@id='NomeParte']").send_keys(nome)

browser.find_element_by_xpath("//*[@id='btnBuscarProcPublico']").click()

# Searches for the text of the last icon - the last page button
element = browser.find_element_by_xpath("//*[@id='divTabela']/div[2]/div[2]/div[4]/div[2]/ul/li[9]/a").text
element
'»'

This site when searching for terms paginates results and always shows as the last pagination button the "»" button.

The next to last button in the case will be "›"

So I need to capture the button text always twice before the last one. Here is this case the number "8", to automate page change - I will know how many clicks on next page will be needed

Please, when I search Xpath how do I capture the element two positions before?


回答1:


I know this is not an answer to the original question. But clicking the next button several times is not a good practice. I checked the network traffic and see that they are calling their API url with offset parameter. You should be able to use this URL with proper offset as you need.

If you really need to access the last but two, you need to get the all navigation buttons first and then access by indexing as follows.

    elems = self.browser.find_elements_by_xpath(xpath)
    elems[-2]

EDIT

I just tested their API and it works with proper cookie value given. This way is much faster than automation using Selenium. Use Selenium just to extract cookie value to be used in the header of the web request.



来源:https://stackoverflow.com/questions/58863479/in-selenium-when-i-search-xpath-how-do-i-capture-the-element-two-positions-befo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!