程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python+selenium gets the solution that the element text is empty none

編輯:Python

Use some 8 City practice selenium When , There is one " Load more " The button , Usually invisible . adopt selenium Get this text content is always empty

Invalid method

1\ text attribute

        element.text

2\ Although in the browser F12 In the console , You can get the text content of this element , But with selenium send out js Get content is still empty

Effective method  

1\ Determine whether the element is empty

2\ terms of settlement

(1)selenium Only interact with visible elements , So the text to get the hidden element is empty None. You can modify the element related attributes to be visible

(2) adopt get_attribute() Method to get the element text

         When getting the text information of hidden elements , have access to get_attribute() Method , adopt textContent、innerText、innerHTML And so on .

innerHTML Will return the inside of the element HTML, All inclusive HTML label .

textContent and innerText Set gray to get the text content , It doesn't include HTML label .textContent yes W3C Compatible text content properties , however IE I won't support it ;innerText No W3C DOM The designated content of , however FireFox I won't support it .

from selenium import webdriver
from selenium.webdriver.common.by import By
import time
driver = webdriver.Firefox(keep_alive=True)
driver.maximize_window()
driver.get("https://XXXXX.58.com/pinpaigongyu/")
xpath = (By.XPATH,'//div[@class="loadbtn "]')
element = driver.find_element(*xpath)
text = element.get_attribute("innerText")
# For invisible elements , Although in the browser F12 The console of can get text , however selenium Sent js Still can't get
# script = "arguments[0].textContent"
# text = driver.execute_script(script,element)
print(text)
time.sleep(4)
driver.quit()


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved