【问题标题】:How do I grab the price using Selenium in python? [duplicate]如何在 python 中使用 Selenium 获取价格? [复制]
【发布时间】:2021-11-05 05:47:03
【问题描述】:

这里是 Selenium 和 Python 的新手。我正在尝试获取商品的价格。

但我收到此错误:'str' 对象不可调用。我做错了什么?

URL of the item

from bs4 import BeautifulSoup
import requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

url = "https://www.staples.ca/products/959340-en-dr-pepper-355-ml-cans-12-pack"

s=Service('C:/Users/teddy/OneDrive/Desktop/chromedriver.exe')
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--incognito')
options.add_argument('--headless')
driver = webdriver.Chrome(service=s)

driver.get(url)
get_elements = driver.find_element(By.XPATH("//span[@data-product-id='2151359512645'']"))

# print(get_elements.text)

【问题讨论】:

  • 您在 xpath 的末尾添加了一个额外的引号。应该是//span[@data-product-id='2151359512645']

标签: python selenium


【解决方案1】:

回答您的问题,您的 xpath 末尾有一个额外的引号,如@pmadhu 所述。此外,您应该等待<span> 元素可以使用get_elements = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@data-product-id='2151359512645']"))) 进行点击,它应该会消除错误。带导入的代码:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

get_elements = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@data-product-id='2151359512645']")))

【讨论】:

  • 你能解释一下你是怎么知道你必须等待 span 元素可以点击的吗?
【解决方案2】:

您应该先点击一个模式弹出窗口。

另外,您拥有的 XPath 是 numeric,它永远不会是一致的。

请在 XPath 上使用 CSS。

代码:

from bs4 import BeautifulSoup
import requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

url = "https://www.staples.ca/products/959340-en-dr-pepper-355-ml-cans-12-pack"

s=Service('C:/Users/teddy/OneDrive/Desktop/chromedriver.exe')
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--incognito')
options.add_argument('--headless')
driver = webdriver.Chrome(service=s)

driver.maximize_window()
wait = WebDriverWait(driver, 30)

driver.get("https://www.staples.ca/products/959340-en-dr-pepper-355-ml-cans-12-pack")

try:
    wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".Modal__Title+span.icon--close"))).click()
    print('Clicked on close modal pop up')
except:
    pass

price = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.money-details+span"))).text
print(price)

进口:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

输出:

Clicked on close modal pop up
$7.29

【讨论】:

  • 你能解释一下这条评论是什么意思吗? “你拥有的 XPath 是数字的,它永远不会是一致的。”
猜你喜欢
  • 2016-05-06
  • 2018-09-29
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多