【问题标题】:In selenium, when I search Xpath how do I capture the element two positions before?在 selenium 中,当我搜索 Xpath 时,如何捕获元素之前的两个位置?
【发布时间】:2019-11-14 18:22:07
【问题描述】:

在 Python 3 和 selenium 中,我有这个脚本可以自动搜索包含公共信息的站点中的术语

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
'»'

此站点在搜索术语时对结果进行分页,并始终将“»”按钮显示为最后一个分页按钮。

案例中倒数第二个按钮将是“›”

所以我需要在最后一个之前捕获按钮文本两次。这是这种情况下的数字“8”,用于自动更改页面 - 我会知道需要多少次点击下一页

请问,当我搜索 Xpath 时,我如何捕获之前两个位置的元素?

【问题讨论】:

    标签: python selenium xpath tags selenium-chromedriver


    【解决方案1】:

    我知道这不是原始问题的答案。 但是多次单击下一步按钮并不是一个好习惯。 我检查了网络流量,发现他们正在使用 offset 参数调用他们的 API url。您应该能够根据需要使用具有适当偏移量的此 URL。

    如果你真的需要访问最后两个,你需要先获取所有导航按钮,然后通过索引访问,如下所示。

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

    编辑

    我刚刚测试了他们的 API,它适用于给定的适当 cookie 值。 这种方式比使用 Selenium 的自动化要快得多。 使用 Selenium 只是为了提取 cookie 值以在 Web 请求的标头中使用。

    【讨论】:

    • 非常感谢@David Piao。我可以在上面编辑我的问题并将解决方案尝试与您的方法一起使用吗?我在使用请求时遇到了困难。我应该使用 POST 吗?
    • 您显示的黑屏图像不是 Inspect 元素,对吧?是软件吗?
    • 黑屏来自Postman——非常好的API测试工具
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多