Python Selenium -无法从网页检索价格

wnavrhmk  于 2022-12-23  发布在  Python
关注(0)|答案(1)|浏览(123)

我试图从网上商店的产品检索价格,但找不到正确的代码来获得它。
我要提取的产品价格:https://www.berger-camping.nl/zoeken/?q=3138522088064
这是一行代码,我必须(尝试)和检索价格:

Prijs_BergerCamping = driver.find_element(by=By.XPATH, value='//div[@class="prod_price__prod_price"]').text
        print(Prijs_BergerCamping)

有什么建议我似乎错过了什么?

uttx8gqw

uttx8gqw1#

您的代码是正确的。
我猜你所缺少的就是等待元素的可见性。
此代码适用于:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")

webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(options=options, service=webdriver_service)
wait = WebDriverWait(driver, 20)

url = "https://www.berger-camping.nl/zoeken/?q=3138522088064"
driver.get(url)

price = wait.until(EC.visibility_of_element_located((By.XPATH, '//div[@class="prod_price__prod_price"]'))).text
print(price)

输出为:

79,99 €

但是你还需要关闭cookie横幅和选择商店对话框(至少我看到了)。

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")

webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(options=options, service=webdriver_service)
wait = WebDriverWait(driver, 20)

url = "https://www.berger-camping.nl/zoeken/?q=3138522088064"
driver.get(url)

wait.until(EC.element_to_be_clickable((By.ID, "onetrust-accept-btn-handler"))).click()
wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@style] //*[contains(@class,'uk-close')]"))).click()
price = wait.until(EC.visibility_of_element_located((By.XPATH, '//div[@class="prod_price__prod_price"]'))).text
print(price)

相关问题