Selenium 通过 class 查找元素,但 returns 为空字符串。怎么修?

Selenium finds element by class, but returns empty string. How to fix?

该代码试图显示一个城市的天气预报。它能够找到包含内容的 class,但它打印出一个空字符串。为什么会这样?我该如何更改我的代码以不获取空字符串?

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

s=Service("C:\Program Files (x86)\chromedriver.exe")
browser = webdriver.Chrome(service=s)

city = str(input("Enter a city"))

url="https://www.weather-forecast.com/locations/"+city+"/forecasts/latest"
browser.get(url)
browser.maximize_window()

content = browser.find_element(By.CLASS_NAME, "b-forecast__table-description-content")
print(content.text)

你已经足够接近了。内容实际上在祖先 <p> 标签的后代 <span> 内。


要打印所有需要的文本,您必须诱导 for the visibility_of_all_elements_located() and you can use either of the following :

  • 使用CSS_SELECTOR:

    city = "Dallas"
    driver.get("https://www.weather-forecast.com/locations/"+city+"/forecasts/latest")
    print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "p.b-forecast__table-description-content > span.phrase")))])
    
  • 使用 XPATH:

    city = "Dallas"
    driver.get("https://www.weather-forecast.com/locations/"+city+"/forecasts/latest")
    print([my_elem.get_attribute("innerText") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//p[@class='b-forecast__table-description-content']/span[@class='phrase']")))])
    
  • 控制台输出:

    ['Heavy rain (total 0.8in), heaviest during Tue night. Warm (max 86°F on Mon afternoon, min 66°F on Tue night). Winds decreasing (fresh winds from the S on Sun night, light winds from the S by Mon night).', 'Light rain (total 0.3in), mostly falling on Fri morning. Warm (max 77°F on Wed afternoon, min 57°F on Wed night). Wind will be generally light.', 'Light rain (total 0.1in), mostly falling on Sat night. Warm (max 84°F on Sat afternoon, min 43°F on Sun night). Winds decreasing (fresh winds from the N on Sun afternoon, calm by Mon night).', 'Mostly dry. Warm (max 70°F on Wed afternoon, min 48°F on Tue night). Wind will be generally light.']
    
  • 注意:您必须添加以下导入:

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