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