ollama ollama - 1 year ago 70
HTML Question

Get href from leftmost column in table with XPath

I am attempted to extract

text from a table here: https://en.wikipedia.org/wiki/List_of_first-person_shooters

Here is the top of the table:

<table class="wikitable sortable" style="font-size: 85%; text-align: left;">
<tr style="background: #ececec">
<th>Release Date</th>
<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>
<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>
<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>

The following XPath query obtains the href text from the table, but I only want the first column from each row. Is this possible with XPath, preferable without counters? I am using Python library

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',

However, I would like only the first item in each row

Answer Source

I only want the first column from each row

This XPath,

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

will select only the a/@href found in the first column of each tr:


regardless of whether the first column is a td or th.

If you're only interested in the td entries, then you can replace the * with td,

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

then you'll select the a/@href attributes with these values:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download