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       # 返回字符串格式

 

转载于:https://www.cnblogs.com/52forjie/p/10315523.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值