如何在Python(SoRy)中定义XPath命令以接受代码中所指示的位置的任何数字。我已经试过 * 或 any() 在那个位置。
*
any()
table = response.xpath('//*[@id="olnof_**here I want to accept any value**_altlinesodd"]/tr[1]/TD[1]/A[1]')
你可以试试下面的变通方法:
'//*[starts-with(@id, "olnof_") and contains(@id, "_altlinesodd")]/tr[1]/TD[1]/A[1]'
ends-with(@id, "_altlinesodd") 在这种情况下,套房更好,但scrapy不支持 ends-with 语法,所以 contains 代替使用
ends-with(@id, "_altlinesodd")
ends-with
contains
现在假设你有任何类似的,所以你可以试试这个。 x_path = '//*[@id="olnof_{}_altlinesodd"]/tr[1]/TD[1]/A[1]' x_path.format("put your any here, may b from rand function or extracting the value from somewhere else.") 然后, table = response.xpath(x_path) 这就行了。
x_path = '//*[@id="olnof_{}_altlinesodd"]/tr[1]/TD[1]/A[1]'
x_path.format("put your any here, may b from rand function or extracting the value from somewhere else.")
table = response.xpath(x_path)
你可以这样做 regular expressions :
table = response.xpath('//*[re:test(@id, "^olnof_.+_altlinesodd$")]/tr[1]/TD[1]/A[1]')