【问题标题】:How to simulate a button click in selenium?如何模拟硒中的按钮点击?
【发布时间】:2020-10-02 19:26:24
【问题描述】:

我目前正在学习硒。我试图模拟来自 url“https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries”的 csv 文件的按钮点击。

我做到了:

Right click the csv icon
Inspect and copy the full xpath

然后我使用了以下代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os

driver = webdriver.Chrome()

url = 'https://worldpopulationreview.com/countries/countries-by-gdp'
driver.get(url)

xpath = '/html/body/div[1]/div/div[1]/div[2]/div[2]/div[1]/div/div/div/div[2]/div[1]/a[2]'

btn = driver.find_element_by_xpath(xpath)
btn.click()

# df = pd.read_csv(os.path.expanduser('~/Downloads/data.csv'))
# print(df.head())
# driver.close()

错误

WebDriverException: Message: unknown error: Element <a>...</a> is not clickable at point (1070, 879). Other element would receive the click: <div id="google_ads_iframe_/15184186/worldpopulationreview_adhesion_0__container__" style="border: 0pt none;">...</div>
  (Session info: chrome=85.0.4183.121)
  (Driver info: chromedriver=2.42.591059 (a3d9684d10d61aa0c45f6723b327283be1ebaad8),platform=Mac OS X 10.15.7 x86_64)

尝试

我尝试了多次使用不同的 xpath,但无济于事。如何模拟这个特定网站的按钮点击?

【问题讨论】:

  • 您仔细阅读错误信息了吗?它说了什么?尝试单击时您是否查看过该页面?你看到了什么?

标签: python selenium-webdriver


【解决方案1】:

诱导WebDriverWait() 并等待element_to_be_clickable() 和后面的css选择器。

driver.get("https://worldpopulationreview.com/countries/countries-by-gdp")
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"a[download='csvData.csv']"))).click()

您需要导入以下库。

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

【讨论】:

    【解决方案2】:

    有时 selenium 无法点击某个元素,如果有东西挡住了。在这种情况下,您可以使用 javascript。但首先我会等待元素可点击。

    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
    from selenium.webdriver.common.keys import Keys
    import os
    
    driver = webdriver.Chrome()
    
    url = 'https://worldpopulationreview.com/countries/countries-by-gdp'
    driver.get(url)
    
    xpath = '/html/body/div[1]/div/div[1]/div[2]/div[2]/div[1]/div/div/div/div[2]/div[1]/a[2]'
    
    # btn = driver.find_element_by_xpath(xpath)
    btn = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, "//a[@download='csvData.csv']")))
    driver.execute_script("arguments[0].click();", btn)
    # btn.click()
    
    # df = pd.read_csv(os.path.expanduser('~/Downloads/data.csv'))
    # print(df.head())
    # driver.close()
    

    【讨论】:

    • 它有效,但下载的是 json 而不是 csv。如何下载csv?
    • @MilkyWay001 我更新了您提供的 xpath 以定位 csv。
    猜你喜欢
    • 1970-01-01
    • 2016-06-14
    • 2021-12-13
    • 1970-01-01
    • 2020-04-27
    • 2010-12-20
    • 1970-01-01
    • 2015-06-28
    • 2012-12-16
    相关资源
    最近更新 更多