python - 查看标签之间的 html 文本(python、lxml、urllib、xpath)

标签 python html xpath lxml urllib

我正在尝试解析一些 html,并且想要检索标签之间的实际 html,但我的代码却给了我我认为是元素的位置。

这是迄今为止我的代码:

import urllib.request, http.cookiejar
from lxml import etree
import io
site = "http://somewebsite.com"


cj = http.cookiejar.CookieJar()
request = urllib.request.Request(site)
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
request.add_header('User-agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0')
html = etree.HTML(opener.open(request).read())

xpath = "//li[1]//cite[1]"
filtered_html = html.xpath(xpath)
print(filtered_html)

这是 html 的一部分:

<div class="f kv">
<cite>
www.
<b>hello</b>
online.com/
</cite>
<span class="vshid">
</div>

目前我的代码返回:

[<Element cite at 0x36a65e8>, <Element cite at 0x36a6510>, <Element cite at 0x36a64c8>]

如何提取 cite 标签之间的实际 html 代码?如果我将“/text()”添加到 xpath 的末尾,它会让我更接近,但它会遗漏 b 标签中的内容。我的最终目标是让我的代码给我“www.helloonline.com/”。

谢谢

最佳答案

使用//text()从给定位置获取所有文本元素:

text = filtered_html.xpath('//text()')
print ''.join(t.strip() for t in text)  # prints "www.helloonline.com/"

关于python - 查看标签之间的 html 文本(python、lxml、urllib、xpath),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14093250/

相关文章:

java : generating xpath using string matcher regex

python - 如何创建python函数的副本

python - __init__,继承和可变参数

javascript - HTML5 canvas 基于滚动的动画吸引和脱离

PHP 图像三角

xml - XPath:匹配多个 child 之一

python - 如何在 Tensorflow 中更新二维张量的子集?

python - 如何使用python获取矩阵中某个值周围的框的左上角和右下角坐标?

javascript - 滑动滑动显示垂直但水平工作

c# - Xpath/C#,从多个 namespace 获取数据