python - 使用 XPath 从表中最左边的列获取 href

标签 python html xml xpath lxml

我试图从此处的表中提取 href 文本:https://en.wikipedia.org/wiki/List_of_first-person_shooters

这是表格的顶部:

<table class="wikitable sortable" style="font-size: 85%; text-align: left;">
<tr style="background: #ececec">
<th>Title</th>
<th>Developer</th>
<th>Platform(s)</th>
<th>Release Date</th>
</tr>
<tr>
<th><i><a href="/wiki/007_Legends" title="007 Legends">007 Legends</a></i></th>
<td><a href="/wiki/Eurocom" title="Eurocom">Eurocom</a>, <a href="/wiki/Activision" title="Activision">Activision</a></td>
<td>PS3, X360, Wii U, WIN</td>
<td>2012-10-16</td>
</tr>
<tr>
<th><i><a href="/wiki/007:_Quantum_of_Solace" title="007: Quantum of Solace">007: Quantum of Solace</a></i></th>
<td><a href="/wiki/Treyarch" title="Treyarch">Treyarch</a>, <a href="/wiki/Beenox" title="Beenox">Beenox</a></td>
<td>DS, PS3, Wii, WIN, X360</td>
<td>2008-10-31</td>
</tr>
<tr>
<th><i><a href="/wiki/3D_Monster_Chase" title="3D Monster Chase">3D Monster Chase</a></i></th>
<td><a href="/w/index.php?title=Romik&amp;action=edit&amp;redlink=1" class="new" title="Romik (page does not exist)">Romik</a></td>
<td>AMSCPC, ZX</td>
<td>1985</td>
</tr>

以下 XPath 查询从表中获取 href 文本,但我只需要每一行的第一列。使用 XPath 是否可行,最好不要使用计数器?我正在使用 Python 库 lxml:

tree.xpath('//table[@class="wikitable sortable"]//a/@href')

检索:

['/wiki/007_Legends', '/wiki/Eurocom', '/wiki/Activision', '/wiki/007:_Quantum_of_Solace', '/wiki/Treyarch', '/wiki/Beenox', '/wiki/3D_Monster_Chase', '/w/index.php?title=Romik&action=edit&redlink=1', '/wiki/Ace_of_Spades_(video_game)', '/w/index.php?title=Ben_Aksoy&action=edit&redlink=1', '/wiki/Alcatraz:_Prison_Escape', '/wiki/Zombie_Studios', '/wiki/CodeRED:_Alien_Arena', '/w/index.php?title=COR_Entertainment&action=edit&redlink=1', '/wiki/FreeBSD', '/wiki/Alien_Breed_3D', '/wiki/Team17', '/wiki/Alien_Breed_3D_II:_The_Killing_Grounds', '/wiki/Team17', 

但是,我只想要每行中的第一项

最佳答案

I only want the first column from each row

这个 XPath,

 //table[@class="wikitable sortable"]//tr/*[1]//a/@href

将仅选择在每个 tr 的第一列中找到的 a/@href:

/wiki/007_Legends
/wiki/007:_Quantum_of_Solace
/wiki/3D_Monster_Chase

不管第一列是td还是th

如果您只对 td 条目感兴趣,那么您可以将 * 替换为 td

//table[@class="wikitable sortable"]//tr/td[1]//a/@href

然后您将选择具有这些值的 a/@href 属性:

/wiki/Eurocom
/wiki/Activision
/wiki/Treyarch
/wiki/Beenox
/w/index.php?title=Romik&action=edit&redlink=1

关于python - 使用 XPath 从表中最左边的列获取 href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39339188/

相关文章:

html - 用户未登录时显示的子菜单

html - CSS 动态调整 Div 大小以适应内容?

php - XPath 一次选择多个元素?

javascript - AngularJS 获取 XML 子节点

Python Pandas,应用函数

带逗号/列表的 Python 切片表示法

python - 更新数据存储应用引擎中的实体

javascript - 在javascript中为乘法时间表添加起点和终点

python - 如何向 Intersango API 发出请求

使用 ElementTree 和请求进行 XML 解析