from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('https://www.worldometers.info/coronavirus/country/canada/')
time.sleep(1)
button = driver.execute_script("window.scrollTo(0, 5500)")
button1 = driver.find_element_by_xpath('/html/body/div[4]/div[2]/div[1]/div[8]/div/div[9]/a/button')
button1.click()
尝试使用xpath单击此按钮,但似乎没有单击该按钮来扩展网页。我首先尝试通过xpath复制无效,然后又复制了完整的xpath无效。之后,我尝试按名称查找并在按钮上输入文字,然后单击按钮。但是,这些方法都没有实际起作用,并单击了按钮。那么,如何单击此按钮以扩展网页,从而使我可以抓取更多网页?
答案 0 :(得分:0)
问题在于尽管此按钮现在已在页面中呈现,但该按钮并未处于“可点击状态”。 为了避免这种情况,您必须添加一个显式等待,告诉驱动程序等待,直到状态更改为可点击为止。
尝试改用此代码:
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get('https://www.worldometers.info/coronavirus/country/canada/')
time.sleep(1)
button = driver.execute_script("window.scrollTo(0, 5500)")
button1 = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[4]/div[2]/div[1]/div[8]/div/div[9]/a/button')))
button1.click()
答案 1 :(得分:0)
要点击View more News
并诱导WebdriverWait
,然后等待presence_of_element_located()
并跟随 css 选择器。
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get('https://www.worldometers.info/coronavirus/country/canada/')
button=WebDriverWait(driver,20).until(EC.presence_of_element_located((By.CSS_SELECTOR,"a.load-more__btn>.btn")))
button.location_once_scrolled_into_view
button.click()
或使用以下 xpath
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get('https://www.worldometers.info/coronavirus/country/canada/')
button=WebDriverWait(driver,20).until(EC.presence_of_element_located((By.XPATH,"//a[@class='load-more__btn']/button[@class='btn']")))
button.location_once_scrolled_into_view
button.click()