【问题标题】:iterate through classes in selenium python遍历 selenium python 中的类
【发布时间】:2016-10-12 08:57:39
【问题描述】:

** 我在弹出页面上运行它。因此不能简单地使用“入口”类,因为它与原始页面冲突。

我想遍历类以从“条目”类中挑选出文本

from selenium import webdriver
driver=webdriver.Firefox()

当我从 chrome 中选择这个元素的 xpath 时,它是这样来的

但这不适用于driver.find_element_by_xpath(/html/body/span/div[1]/div/div[3])

但下面的一个是有效的,但它给了我日期、标题等。但我只想要文本

driver.find_element_by_class_name("ui_overlay").text 

【问题讨论】:

    标签: python selenium web-scraping


    【解决方案1】:

    试试这个 xpath 它将正确定位:

    ".//span[@class = 'ui_overlay ui_modal ']//div[@class='entry']" 
    

    使用示例:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    import time
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    driver = webdriver.Chrome("C:\Jars\chromedriver.exe")
    driver.maximize_window()
    url="https://www.tripadvisor.com/Airline_Review-d8729164-Reviews-Cheap-Flights-TAP-Portugal#REVIEWS"
    driver.get(url)
    
    wait = WebDriverWait(driver, 10)
    
    langselction = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.sprite-date_picker-triangle")))
    langselction.click()
    driver.find_element_by_xpath("//div[@class='languageList']//li[normalize-space(.)='Portuguese first']").click()
    gt= driver.find_elements(By.CSS_SELECTOR,".googleTranslation>.link")
    for i in gt:
        i.click()
        time.sleep(2)
        x = driver.find_element(By.XPATH, ".//span[@class = 'ui_overlay ui_modal ']//div[@class='entry']")
        print x.text
        driver.find_element_by_class_name("ui_close_x").click()
        time.sleep(2)
    

    会打印相应的文字

    【讨论】:

    • 我怎样才能得到文本。我在使用这个 后得到这个输出
    • @thebadguy 摇滚!。但是你能告诉我你是怎么得到那个xpath的吗?在我的 chrome 中,当我右键单击并复制 xpath 时,它只是 /html/body/span/div[1]/div/div[3]
    • 基本上它是在创建自定义 xpath..而不是从 chrome 复制 xpath。也请接受它作为答案。
    • @thebadguy 代码异常失败stackoverflow.com/questions/40013400/…
    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 2012-08-16
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2018-07-20
    相关资源
    最近更新 更多