Python: Using xpath locally / on a specific element Python: Using xpath locally / on a specific element python python

Python: Using xpath locally / on a specific element


Your xpath starts with a slash (/) and is therefore absolute. Add a dot (.) in front to make it relative to the current element i.e.

links = table.xpath(".//a[contains(@href, 'http://www.example.com/filter/')]")


Another option would be to ask directly for elements inside your table.For instance:

tree = lxml.html.parse(some_response)links = tree.xpath("//table[**criteria**]//a[contains(@href, 'http://www.example.com/filter/')]")

Where **criteria** is necessary if there are many tables in the page. Some possible criteria would be to filter based on the table id or class. For instance:

links = tree.xpath("//table[@id='my_table_id']//a[contains(@href, 'http://www.example.com/filter/')]")