我试图得到一个值,是由网站后点击一个按钮。
网址如下: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()
您可以简单地添加一个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)
以下代码使用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()