开门见山,直接举例:
#初始路径:
xpath='//div[i]/div[1]/a'
#第一个div中的i是变量
x=[1,2,3,4,5]
for i in x:
xpath='//div[i]/div[1]/a'
print(xpath)
#我想遍历1到5,这是指定行不通的
#直接改为:
x=[1,2,3,4,5]
for i in x:
xpath='//div[str(i)]/div[1]/a'
print(xpath)
#也是不行的
解决办法如下:
x=[1,2,3,4,5]
for i in x:
xpath='//div['+str(i)+']/div[1]/a'
print(xpath)
完美解决。
原因如下:
The basic building block of XPath 3.1 is the expression, which is a string of [Unicode] characters; the version of Unicode to be used is implementation-defined.
XPath 3.1的基本构建模块是表达式,它以[Unicode]字符的字符串形式出现,直接来个整型的数字(1/2/3)指定不行,必须转化为str型。
两个加号是将前后字符串分别连接。
>>> print ‘red’ + str(3) red3
>>> print ‘red’ + ‘yellow’
Redyellow
>>> print ‘red’ * 3
Redredred
>>> print ‘red’ + 3
Traceback (most recent call last):
File “”, line 1, in
TypeError: cannot concatenate ‘str’ and ‘int’ objects