我有这个代码:
from keyboard import press_and_release
from selenium import webdriver
from selenium.webdriver.common.by import By
url = 'https://www.yr.no/nb'
def weather(url, webdriver):
webdriver.get(url) # Goes to the HTML-page of the given URL
for li_values in webdriver.find_elements(By.CSS_SELECTOR, "ol.daily-weather-list__intervals li"):
print(li_values.text + "n")
def forecast():
print('Hello, I can search up the weather for you.')
driver = webdriver.Chrome(r"C:UsersAmalieDownloadschromedriver_win32chromedriver.exe") # Open Google Chrome
driver.get(url) # Goes to the HTML-page of the given URL
while True:
inp = input('Where shall I search? Enter a place in :').capitalize() # Ask for input
print('Alright, checking the weather in ' + inp + '...')
"Search for a place"
driver.find_element_by_id("page-header__search-button").click() # Find and click on search input box
driver.find_element_by_id("page-header__search-input").send_keys(inp) # Enter input
press_and_release('enter') # Click enters
driver.find_element_by_xpath('//*[@id="page-header__search"]/ol/li[1]').click() # Click on 1st suggested option
break
cURL = driver.current_url
weather(cURL, driver)
driver.close()
driver.quit()
forecast()
这给了我这个输出:
Hello, I can search up the weather for you.
Where shall I search? Enter a place in :bergen
Alright, checking the weather in Bergen...
I dag 14. juni
Ettermiddag: skyet
Kveld: skyet
Maksimum/minimum temperatur:
13°/12°
Nedbør
0,5mm
Vind:
5
m/s
Se time for time
Ettermiddag: skyet
Kveld: skyet
Tirsdag 15. juni
Natt: regn
Morgen: regn
Ettermiddag: delvis skyet
Kveld: skyet
Maksimum/minimum temperatur:
13°/10°
Nedbør
4,6mm
Vind:
4
m/s
Se time for time
Natt: regn
Morgen: regn
Ettermiddag: delvis skyet
Kveld: skyet
Onsdag 16. juni
Natt: skyet
Morgen: regn
Ettermiddag: regn
Kveld: regn
Maksimum/minimum temperatur:
16°/10°
Nedbør
10mm
Vind:
9
m/s
Se time for time
Natt: skyet
Morgen: regn
Ettermiddag: regn
Kveld: regn
等等。。。
我如何选择只打印今天、明天等的数据,如下所示:
I dag 14. juni
Ettermiddag: skyet
Kveld: skyet
Maksimum/minimum temperatur:
13°/12°
Nedbør
0,5mm
Tirsdag 15. juni
Natt: regn
Morgen: regn
Ettermiddag: delvis skyet
Kveld: skyet
Maksimum/minimum temperatur:
13°/10°
Nedbør
4,6mm
我知道xpath,但我认为我必须使用标识符或类似的东西,但我对HTML非常陌生,所以我不知道是否已经有了这个函数,或者我是否必须自己编写代码。
例如,要从列表中获取前两项,可以执行以下操作:
def weather(webdriver):
webdriver.get(url) # Goes to the HTML-page of the given URL
list_xpath = "//ol[@class='daily-weather-list__intervals']/li[@class='daily-weather-list-item']"
all_items = webdriver.find_elements_by_xpath(list_xpath)
for li_values in all_items[:2]:
print(li_values.text + "n")