[英]Selenium with Python: Using a loop in read text
I am trying to pass the i parameter into the xpath expression, however it seems the syntax is not correct.我试图将 i 参数传递到 xpath 表达式中,但语法似乎不正确。
i = 1
while i < 9:
day1Temp = driver.find_element(By.XPATH, "//*[@id='wob_dp']/div[", i, "]/div[3]/div[1]/span[1]")
print(day1Temp.text)
Can anyone suggest what is wrong here?谁能建议这里出了什么问题?
to parse i
, you can use f-string
like below:要解析
i
,您可以使用如下所示f-string
:
i = 1
while i < 9:
day1Temp = driver.find_element(By.XPATH, f"//*[@id='wob_dp']/div[{i}]/div[3]/div[1]/span[1]")
This is how you can fix your code.这就是修复代码的方法。 Also don't forget to increment
i
也不要忘记增加
i
i = 1
while i < 9:
day1Temp = driver.find_element(By.XPATH, "//*[@id='wob_dp']/div[%d]/div[3]/div[1]/span[1]" % i)
print(day1Temp.text)
i += 1
You have initialized你已经初始化
i = 1
Hence i
is of type int因此
i
是int类型
Where as within the xpath you need to pass i
as a string .在 xpath 中,您需要将
i
作为字符串传递。 So you have to convert the type of i as string .所以你必须将i的类型转换为string 。
Using f-strings
your effective code block will be:使用
f-strings
你的有效代码块将是:
i = 1
while i < 9:
day1Temp = driver.find_element(By.XPATH, f"//*[@id='wob_dp']/div[{str(i)}]/div[3]/div[1]/span[1]")
print(day1Temp.text)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.