selenium etree xpath使用總結


1,首先使用selenium xpath

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from lxml import etree

#下面代碼主要是讓selenium使用無界面的chrome瀏覽器
chrome_options = Options()    
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(chrome_options=chrome_options)

driver.get(url)
#當用driver使用get_attribute時,獲取到的是整個column標簽下面所有的html,是字符串格式----不對etree對象有用
column = driver.find_element_by_class_name('column').get_attribute(
'innerHTML')
html = etree.HTML(column)   #使用etree變成lxml格式
html.xpath('//li[@class="first_f"]//div[@class="msg"]/a[2]/text()')
# 獲取到的值是文本['內容'],列表格式的字符串()

如果要獲取標簽里面的html,
details = html.xpath('//li[@id="{}"]//div[@class="reply_c"]/p'.format(reply_id))[0]
details = etree.tostring(details, encoding="utf-8", pretty_print=True, method="html") # 獲取到的是標簽的html,是byte類型
details = details.decode('utf-8') if details else None       # 返回字符串格式
 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM