from selenium import webdriver driver = webdriver.Chrome() url="xxx" driver.get(url)
driver.find_element(By.ID,'id')
driver.find_element(By.NAME,'name')
driver.find_element(By.CLASS_NAME,'class_name')
driver.find_element(By.TAG_NAME,'tag_name')
driver.find_element(By.XPATH,'xpath')
driver.find_element(By.CSS_SELECTOR,'css_selector')
driver.find_element(By.LINK_TEXT,'link_text')
driver.find_element(By.PARTIAL_LINK_TEXT,'partial_link_text')
title = driver.title print(title)
url = driver.current_url print(url)
input_size = driver.find_element(By.ID,'id').size print(input_size)
注意:不能获取到输入框的文本信息,下文会介绍怎么获取
text = driver.find_element(By.ID,'id').text print(text)
attribute = driver.find_element(By.ID,'id').get_attribute('type') print(attribute)
result = driver.find_element(By.ID,'id').is_displayed() print(result)
driver.find_element(By.ID,'id').send_keys("xxx")
driver.quit()
上面已经提到了通过text不能获取到输入框的数据,于是我们有下面三种方式去获取
driver.find_element(By.ID,'id').send_keys('xxx')
result = driver.execute_script('return $("#id").attr("name");') print(result)
直接通过js获取定位的数据,通过.val()
的方法获取
result = driver.execute_script('return $("#id").val();') print(result)
通过selenium
的get_attribute
获取
result = driver.find_element(By.ID,'id').get_attribute('value') print(result)
后续会逐步更新
这个异常发生在没找到该元素造成的,对于一些定位失败的时候我们就可以处理
from selenium.common.exceptions import NoSuchElementException try: tt = driver.find_element(By.XPATH, '//*[@id="panel"]/div[3]/div/div[1]/div/div/form/div[2]/div[1]/label/div/input').get_attribute('value') tt=tt.replace(" ",",") tt=tt.replace("-",",") # print(tt) driver.find_element(By.NAME,'tag').click() # 点击标签框 # driver.find_element(By.NAME,'tag').clear() # 清空框 driver.find_element(By.NAME,'tag').send_keys(tt) # 自动敲入用户名 # driver.find_element(By.XPATH,'//*[@id="panel"]/div[3]/div/div[1]/div/div/form/div[5]/div/button[1]').click()# 点击“保存”按钮 except NoSuchElementException: print("no page ",ipp)