Xpath。如何获取给定 Selector 的标签名称。废料

Xpath. How do I get tag name given Selector. Scrapy

我有这个 xpath returns 选择器列表。

for i in response.xpath('//*[name()="h2" or name()="h3" or name()="p"]'):
     print i

结果:

<Selector xpath='//*[name()="h2" or name()="h3" or name()="p"]' data=u'<h3 class="fusion-header-tagline"><img s'>
<Selector xpath='//*[name()="h2" or name()="h3" or name()="p"]' data=u'<h3 class="features-title role-element l'>
<Selector xpath='//*[name()="h2" or name()="h3" or name()="p"]' data=u'<h2 style="text-align: center;">Sell you'>
<Selector xpath='//*[name()="h2" or name()="h3" or name()="p"]' data=u'<p>We buy properties in any shape, any p'>
<Selector xpath='//*[name()="h2" or name()="h3" or name()="p"]' data=u'<p>Attempting to sell your house in Marl'>
<Selector xpath='//*[name()="h2" or name()="h3" or name()="p"]' data=u'<h2 style="text-align: center;"><span st'>
<Selector xpath='//*[name()="h2" or name()="h3" or name()="p"]' data=u'<p><img class="aligncenter wp-image-1439'>
<Selector xpath='//*[name()="h2" or name()="h3" or name()="p"]' data=u'<h3><span style="color: #000000;">No com'>
<Selector xpath='//*[name()="h2" or name()="h3" or name()="p"]' data=u'<h3><span style="color: #000000;">You do'>
<Selector xpath='//*[name()="h2" or name()="h3" or name()="p"]' data=u'<h3><span style="color: #000000;">We wil'>
<Selector xpath='//*[name()="h2" or name()="h3" or name()="p"]' data=u'<h3><span style="color: #000000;">No lis'>

如何获取每个选择器的标签名称? IE。 h3, h3, h2, p, p, h2等 我试过了

print name(i)
print i.name()

那是行不通的。 如何正确使用xpath name()获取标签名称?

将您的代码更改为:

for i in response.xpath('//*[name()="h2" or name()="h3" or name()="p"]'):
    print i.xpath('name()')

这将 select 来自每个元素的 name() select 在第一个 xpath

上编辑

Scrapy 中的选择器实际上并不代表 HTML 树中的节点,但必须被视为引用 XPath 或 CSS 选择器结果的抽象。因此,他们也没有标签名称或属性的概念。但是您可以使用 root 属性轻松访问选择器的底层根节点:

for i in response.xpath('//*[name()="h2" or name()="h3" or name()="p"]'):
     print(i.root.tag)