【发布时间】:2015-07-28 06:04:18
【问题描述】:
这个问题以前有人问过,
这是 HTML 数据
<p>
This is some important data
<br>
Even this is data
<br>
this is useful too
</p>
<othertag>
othertag data
</othertag>
<moretag>
moretag data
</moretag>
....
repeating n times
....
我的目标是提取<p></p> 内的数据,而不是被<br> 标签和其他数据分开
这是我的查询
//p//text() | //othertag//text() | //moretag//text()
这给了
('This is is some important data', 'even this data', 'this is useful too',
'othertag data','moretag data')
注意到上面<p>标签文本数据已经在输出中拆分了吗?
我希望将其格式化为正确的单位如下所示,
('This is is some important data even this data this is useful too',
'othertag data','moretag data')
如果不可能, 我至少可以这样得到它吗?
('This is is some important <br> data even this data <br> this is useful too',
'othertag data','moretag data')
我不能使用join 语句,因为很难在变量索引中选择性地加入变量列表值(没有人可以预测会有多少<br> 标记,因此数据可能会拆分变量次数)
我的尝试(在其他用户的帮助下)
string(//p//text()) | //othertag//text() | //moretag//text()
上述查询导致 XPATH 错误
这个也是,
import lxml.html, lxml.etree
ns = lxml.etree.FunctionNamespace(None)
def cat(context, a):
return ''.join(a)
ns['cat'] = cat
这个查询也给出了InvalidType 错误
cat(//p//text()) | //othertag//text() | //moretag//text()
我正在使用 python 2.7
【问题讨论】:
-
您愿意使用其他库吗?您不应该尝试将 html 解析为 xml ,您应该使用为解析 html 构建的库。
-
按照the original answer中的建议修改
cat函数定义为return [''.join(a)] -
@har07 在每种类型有多个标签时将无法按预期工作(请参阅编辑)它将所有
p标签中的所有文本连接成一个字符串。我想要这样("p - text data","othertag data","moretag data","p-text data", "other tag data".....) -
@har07 如果这不可行,我愿意妥协是否可以将内部文本数据作为一个包含
<br>标签的单元来获取。如果可能的话,你能建议吗?