這個問題在這里已經有了答案: TypeError: 'str' object is not callable using Selenium through Python (2 answers) 1 小時前關閉。
Selenium 和 Python 的新手在這里。我正在嘗試獲取商品的價格。
但我收到此錯誤: 'str' object is not callable。我究竟做錯了什么?
物品的網址
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)
uj5u.com熱心網友回復:
回答您的問題,您在 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']")))
uj5u.com熱心網友回復:
有一個模態彈出視窗,您應該先單擊它。
此外,您所擁有的 XPathnumeric永遠不會是一致的。
請在 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/349007.html
