每当我尝试从网站上抓取一个数字并打印时,它总是返回0,即使我延迟它让窗口先加载。这是我的代码,
from selenium import webdriver
import time
url = 'https://hytrack.me/'
browser = webdriver.Chrome(r'C:UserskinetOneDriveDocumentswebscraperchromedriver.exe')
browser.get(url)
text = browser.find_element_by_xpath('//*[@id="stat_totalPlayers"]').text
time.sleep(10)
print(text)
所有我需要它做的是打印一些文本,它需要从一个网站。是我做错了什么,还是我完全错过了什么?
您应该在获取元素之前放置延迟!
from selenium import webdriver
import time
url = 'https://hytrack.me/'
browser = webdriver.Chrome(r'C:UserskinetOneDriveDocumentswebscraperchromedriver.exe')
browser.get(url)
time.sleep(10)
text = browser.find_element_by_xpath('//*[@id="stat_totalPlayers"]').text
print(text)
虽然最好使用显式等待,像这样:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
url = 'https://hytrack.me/'
browser = webdriver.Chrome(r'C:UserskinetOneDriveDocumentswebscraperchromedriver.exe')
wait = WebDriverWait(driver, 20)
browser.get(url)
text = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="stat_totalPlayers"]'))).text
print(text)