从xpath获取文本值

问题描述 投票:0回答:1

为什么我需要使用这段代码从x路径获取文本值

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

with open('restaurants.csv', 'w', encoding='utf-8') as file:
    file.write('name \n')

driver = webdriver.Chrome()
driver.get('https://www.tripadvisor.co.nz/Restaurants-g1811027-Auckland_North_Island.html')
time.sleep(3)

names = driver.find_elements(By.XPATH, "//div[@class='biGQs _P fiohW alXOW NwcxK GzNcM ytVPx UTQMg RnEEZ ngXxk']/a")

with open('restaurants.csv', 'a', encoding='utf-8') as file:
    for name in names:
        file.write(name.text + '\n')
file.close
driver.quit()

但是当我使用原始代码时,它不允许我从 xpath 获取文本值,为什么?

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

with open('restaurants.csv', 'w', encoding='utf-8') as file:
    file.write('name \n')

driver = webdriver.Chrome()
driver.get('https://www.tripadvisor.co.nz/Restaurants-g1811027-Auckland_North_Island.html')
time.sleep(3)

name  = driver.find_elements(By.XPATH,"//div[@class='biGQs _P fiohW alXOW NwcxK GzNcM ytVPx UTQMg RnEEZ ngXxk']/a")

with open('restaurants.csv', 'a', encoding='utf-8') as file:
    for i in range(len(name)):
        file.write(name.text +'\n')
file.close
driver.quit 

谢谢:)

python selenium-webdriver
1个回答
0
投票

问题不在于 XPath,而在于您访问

name
/
names
变量的方式。

在不起作用的代码中,您正在使用

for i in range(len(name)):

但你从不引用

i
。本来应该是

for i in range(len(name)):
    file.write(name[i].text +'\n')
                   ^^^

我认为你最新的代码更容易阅读和遵循。

您应该花一些时间阅读文档中的循环,以更好地理解其中的差异。

© www.soinside.com 2019 - 2024. All rights reserved.