【问题标题】:How do i XPATH or CSS scrape a Web-Page by utilizing the drop-down menu? (Using Selenium)XPATH 或 CSS 如何利用下拉菜单抓取网页? (使用硒)
【发布时间】:2021-08-11 08:28:49
【问题描述】:

好的,所以我对使用 python 编码还很陌生,我无法让我的代码获取一个 url,转到它,然后使用下拉菜单,我希望它选择“全部”选项.哪个是第一个选择

我要抓取的网站页面是:https://www.nba.com/stats/players/advanced/?sort=GP&dir=-1

我的代码正在做它应该做的所有事情,但是当它确实点击下拉菜单时,它只是没有选择菜单上的第一个选项。我很困惑有人可以指导我帮助或更好/更简单的途径来实现我的目标。

感谢任何帮助,

代码:


from selenium.webdriver.support.ui import Select

from bs4 import BeautifulSoup

import pandas as pd

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.Firefox()

url = r"https://www.nba.com/stats/players/advanced/?sort=GP&dir=-1"

driver.get(url)

wait = WebDriverWait(driver, 30)

wait.until(EC.element_to_be_clickable((By.XPATH,"//button[.='I Accept']"))).click()

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/main/div/div/div[2]/div/div/nba-stat-table/div[1]/div/div/select"))).click()```

【问题讨论】:

    标签: python css selenium selenium-webdriver xpath


    【解决方案1】:

    尝试使用下面的 Xpath

     (//div[@class="stats-table-pagination__info"]/select/option)[1]
    

    随着WebDriverWait写点击的概念,这个需要稍微改一下。我们添加 WebDriverWait 的主要原因是基于某些条件等待元素,以便一旦可用就可以单击它。所以试试下面的方法

    # Waiting for the element to be clickable
     1. WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "(//div[@class="stats-table-pagination__info"]/select/option)[1]")))
    
    # Selecting on the element required
     2. select = Select(driver.find_element_by_xpath("(//div[@class="stats-table-pagination__info"]/select/option)[1]"))
        select.select_by_visible_text('All')
    
         
    

    【讨论】:

      【解决方案2】:

      在 selenium 中有一个选择类,用于使用 Select 和选项标签构建的下拉菜单。

      一旦我们像这样定义 webdriver wait wait = WebDriverWait(driver, 30),我们就可以使用 wait 引用类型。您无需再次创建 WebDriverWait 实例。

      代码:

      driver = webdriver.Chrome("C:\\Users\\Inc\\Desktop\\Selenium+Python\\chromedriver.exe")
      driver.maximize_window()
      wait = WebDriverWait(driver, 30)
      driver.get("https://www.nba.com/stats/players/advanced/?sort=GP&dir=-1")
      wait.until(EC.element_to_be_clickable((By.XPATH,"//button[.='I Accept']"))).click()
      
      drop_down = wait.until(EC.element_to_be_clickable((By.XPATH, "//th[text()='PACE']/ancestor::div[@class='nba-stat-table']/preceding-sibling::div/descendant::select")))
      select = Select(drop_down)
      select.select_by_visible_text('All')
      

      【讨论】:

        猜你喜欢
        • 2022-12-19
        • 1970-01-01
        • 2019-09-07
        • 2021-04-18
        • 1970-01-01
        • 2019-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多