获取XST 当前节点的前一个节点和后一个节点

xslt中获取当前节点的前一个节点:

<xsl:value-of select="data:nodeset(preceding-sibling::node()/@period-end-date)[last()]" />

preceding-sibling: 获取当前节点的之前的所有兄弟节点,那么通过last()必然能获取到离它最近并且在它之前的节点。


xslt中获取当前节点的后一个节点:
<xsl:value-of select="data:nodeset(following-sibling::node()/@period-end-date)[first()]" />

following-sibling: 获取当前节点之后的所有兄弟节点,那么通过first()必然能获取离它最近的并且在它之后的节点。
import requests from lxml import etree # 目标URL url = "http://bbs.itheima.com/forum-425-1.html" # 请求头,模拟浏览器行为 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } def fetch_data(url): """发送请求获取页面内容""" response = requests.get(url, headers=headers) if response.status_code == 200: return response.text else: print("Failed to retrieve data") return None def parse(html_content): """解析HTML并提取帖子信息""" tree = etree.HTML(html_content) # 根据提供的信息构建XPath表达式 items = tree.xpath('//tbody[starts-with(@id, "normalthread_")]') posts_info = [] for item in items: try: # 提取标题链接 title_element = item.xpath('.//a[contains(@class, "x") and contains(@class, "xst")]')[0] title = title_element.text link = title_element.attrib['href'] # 提取作者,这里假设作者的名字位于具有 class="y" 的元素内的 c="1" 属性元素 author_elements = item.xpath('.//i[@class="y"]//a[@c="1"]') if author_elements: author = author_elements[0].text.strip() else: author = 'Unknown' # 提取发布时间 post_time = 'Unknown' # 查找具有 c="1" 属性的 <a> 标签,然后查找其后跟随的第一个文本节点 for a_tag in item.xpath('.//i[@class="y"]//a[@c="1"]'): next_text = a_tag.xpath('following-sibling::text()[1]') if next_text: post_time = next_text[0].strip() break # 一旦找到匹配项就退出循环 post_info = { 'title': title, 'link': link, 'author': author, 'post_time': post_time, } posts_info.append(post_info) print(f"Parsed post: {title}") # 调试输出 except Exception as e: print(f"Error while parsing an item: {e}") continue return posts_
最新发布
03-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值