【问题标题】:Get value after button click with python使用python单击按钮后获取值
【发布时间】:2021-12-10 08:39:24
【问题描述】:

我试图在单击按钮后获取网站给出的值。

这里是网站:CPF generator website

可以看到有一个按钮叫做“Gerar CPF”,这个按钮提供了一个点击后出现的数字。

我当前的脚本打开浏览器并获取值,但是我在点击之前从页面获取值,所以该值为空。我想知道点击按钮后是否可以获取值。

from selenium import webdriver
from bs4 import BeautifulSoup
from requests import get

url = "https://www.4devs.net.br/gerador-cpf"

def open_browser():
    driver = webdriver.Chrome("/home/willi/Documents/chromedriver")
    driver.get(url)
    driver.find_element_by_class('btn m-1 btn-primary btn-sm').click()

def get_cpf():
    response = get(url)

    page_with_cpf = BeautifulSoup(response.text, 'html.parser')

    cpf = page_with_cpf.find("input", {"id": "__BVID__61"}).text

    print("The value is: " + cpf)


open_browser()
get_cpf()

【问题讨论】:

    标签: javascript python html jquery css


    【解决方案1】:

    您可以简单地添加一个while 循环,以便在您希望的时间更新该值。例如:

    import time
    from selenium import webdriver
    from bs4 import BeautifulSoup
    from requests import get
    
    url = "https://www.4devs.net.br/gerador-cpf"
    
    def open_browser():
      driver = webdriver.Chrome("/home/willi/Documents/chromedriver")
      driver.get(url)
      driver.find_element_by_class('btn m-1 btn-primary btn-sm').click()
    
    def get_cpf():
      response = get(url)
    
      page_with_cpf = BeautifulSoup(response.text, 'html.parser')
    
      cpf = page_with_cpf.find("input", {"id": "__BVID__61"}).text
    
      print("The value is: " + cpf)
    
    while True:
       open_browser()
       get_cpf()
       time.sleep(your_time_in_s)
    

    【讨论】:

      【解决方案2】:

      以下代码使用 Ruggero 的部分解决方案和 pyperclip 工作:

      import time
      import pyperclip
      from selenium import webdriver
      from selenium.webdriver.common.by import By
      from bs4 import BeautifulSoup
      from requests import get
      import chromedriver_binary  # Adds chromedriver binary to path
      
      url = "https://www.4devs.net.br/gerador-cpf"
      your_time_in_s=2
      
      def open_browser():
          driver = webdriver.Chrome()
          driver.get(url)
          driver.find_element(By.XPATH, '//*[@id="app"]/div/div[2]/div/div/div[3]/div/div[3]/div[1]/div/button[2]').click()
          time.sleep(your_time_in_s)
          driver.find_element(By.XPATH, '//*[@id="__BVID__60"]/div/div/div/button').click()
          print("The value is: " + pyperclip.paste())
      
      while True:
          open_browser()
      

      【讨论】:

        猜你喜欢
        • 2019-05-27
        • 2021-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多