I have the following three buttons that I can't figure out how to grab the text that is inside of them (e.g Outliers). I tried browser.find_element_by_link_text("Outliers").click()
, but got "Unable to locate element" error. How can I do it?
答案 0 :(得分:9)
Another example XPath:
browser.find_element_by_xpath('//button[text()="Outliers"]')
答案 1 :(得分:3)
Try this XPath:
"//button[@class='three-state-item btn btn-default'][.='Outliers']"
.
答案 2 :(得分:0)
有两种方式:
注意:使用normalize-space()方法总是更好,因为即使存在空格,它也能正常工作文本的开头或文本的结尾,因为normalize-space()方法修剪左右侧边空格
答案 3 :(得分:0)
这是对我有用的解决方案:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
CHROME_DRIVER_PATH = Your Driver Path
USERNAME = YOUR USERNAME
PASSWORD = YOUR PASSWORD
SIMILAR_ACCOUNT = "idogsplanet"
class InstaFollower:
def __init__(self, driver_path):
self.driver = webdriver.Chrome(executable_path=driver_path)
def login(self):
self.driver.get("https://www.instagram.com/accounts/login/")
time.sleep(3)
username = self.driver.find_element_by_name("username")
username.send_keys(USERNAME)
password = self.driver.find_element_by_name("password")
password.send_keys(PASSWORD)
time.sleep(2)
login = self.driver.find_element_by_xpath('//*[@id="loginForm"]/div/div[3]/button/div')
login.click()
def find_followers(self):
time.sleep(5)
self.driver.get("https://www.instagram.com/" + SIMILAR_ACCOUNT + "/followers")
followers = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/div/header/section/ul/li[2]/a')
followers.click()
time.sleep(1)
def follow(self):
all_buttons = self.driver.find_elements_by_xpath('//button[normalize-space()="Follow"]')
modal = self.driver.find_element_by_xpath('/html/body/div[5]/div/div/div[2]')
for button in all_buttons:
if button.text != "Follow":
pass
else:
button.click()
time.sleep(2)
time.sleep(10)
self.driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", modal)
self.follow()
bot = InstaFollower(CHROME_DRIVER_PATH)
bot.login()
bot.find_followers()
bot.follow()