selenium通过xpath返回空列表

ifmq2ha2  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(311)

我正在尝试从一个网站使用seleniumwebdriver获取酒店名称和价格。然而,我只得到一个空名单从我的回报。

from selenium import webdriver

url = 'https://www.travelodge.co.uk/search/results?location=Central+London&lat=&long=&action=search&source=l&checkIn=03%2F06%2F21&checkOut=05%2F06%2F21&rooms%5B0%5D%5Badults%5D=1&rooms%5B0%5D%5Bchildren%5D=0'

driver = webdriver.Chrome(executable_path='C:\\Users\\Conor\\Desktop\\diss\\chromedriver.exe')

driver.get(url)   

working = driver.find_elements_by_class_name('hotel-card')

for work in working:
    name = work.find_elements_by_xpath('.//*[@id="main"]/div/div[2]/div[3]/div[2]/div/div/div[2]/div/div[1]/h1/div/a')
    price = work.find_elements_by_xpath('.//*[@id="main"]/div/div[2]/div[3]/div[2]/div/div/div[2]/div/div[2]/div/div/div[1]/h3/span')
    print(name,price)

我使用的类名是否不正确?还是我的写作方式有问题?

flvlnr44

flvlnr441#

使用 dotxpath 你创造了 relative xpath 所以它可以搜索 name,price 仅在所选卡内。但你用 [@id="main"] 它不是在卡片里面,而是在卡片外面——它找不到它。
你应该跳过 [@id="main"] 使用

name  = work.find_element_by_xpath('.//h1/div/a').text
price = work.find_element_by_xpath('.//h3/span').text

print(name, price)

我也把这些都去掉了 divs 因为只有一个 h1 以及 h3 在每张卡片上。
我也用过 find_element 不带字符 s 在word中 element 因为只有一个元素 h1 以及 h3 在每张卡片上。
最小工作代码:

from selenium import webdriver

# import time

url = 'https://www.travelodge.co.uk/search/results?location=Central+London&lat=&long=&action=search&source=l&checkIn=03%2F06%2F21&checkOut=05%2F06%2F21&rooms%5B0%5D%5Badults%5D=1&rooms%5B0%5D%5Bchildren%5D=0'

driver = webdriver.Chrome(executable_path='C:\\Users\\Conor\\Desktop\\diss\\chromedriver.exe')

# driver = webdriver.Chrome() # on my Linux I can run without path

driver.get(url)   

# time.sleep(5)

# cookies = driver.find_element_by_id('ensCloseBanner')

# cookies.click()

working = driver.find_elements_by_class_name('hotel-card')

# print(len(working))

for work in working:
    # find_element without `s` - to get first element
    name = work.find_element_by_xpath('.//h1/div/a').text
    price = work.find_element_by_xpath('.//h3/span').text
    print(name, price)

结果:

London Covent Garden £85.98
London Farringdon £79.98
London Kings Cross Royal Scot £87.98
London Central Euston £79.98
London Central Kings Cross £79.98
London Central Southwark £88.98
London Central Waterloo £79.98
London Central Bank £91.98
London Central City Road £101.98
London Central Marylebone £85.98

相关问题