Dunjeon Dunjeon - 23 days ago 25
Python Question

Xpath pass a variable in a predicate

I need help passing a variable in a predicate via Xpath using Python for a web scrape.

Xpath Predicate path example:

//*[@id="rev_exp_div_1370887"]/table[1]/tbody/tr[1]/td


Not Working Predicate Variable

by_xpath('//*[@id="rev_exp_div_1370887"]/table["' + str(x) + '"]/tbody/tr[1]/td').text


The code passes syntax checks and runs successfully, but doesn't hit the correct table (any at all, in fact) even though x is returning the correct value when I double check it with a print x. It works, of course, if I hard code the value in (shown in the top line of code) so I know the path is correct at least.

Idea, comments or suggestions welcome and appreciated.

Answer

Your /table["' + str(x) + '"] does not need the ".

Try /table[' + str(x) + '] instead.

Comments