2017-02-19 74 views
0

我一直在試圖使用XPath實現了廢料,當我最後一次問這個問題,我會提出我的代碼,並輸出與期望輸出:問題Python和硒獲得元素dispay文本元素刮

代碼:

from re import findall,sub 
from lxml import html 
from time import sleep 
from selenium import webdriver 
from pprint import pprint 
from xvfbwrapper import Xvfb 

def parse(url): 
    response = webdriver.Chrome() 

    response.get(url) 

    otherkeyElement = response.find_element_by_class_name('locu-menu-item-name') 

    thekeyElement = response.find_element_by_css_selector('.locu-widget-wrapper #locu-render-output .locu-menu .locu-menu-item .locu-menu-item-name') 

    gelkeyElement = response.find_element_by_xpath('//*[@id="locu-medium-container"]/div[1]/div/div[1]/div[2]/div[3]/div[1]/div[1]') 

    if otherkeyElement: 
     otherkeyElement 
     pprint(otherkeyElement) 

    if thekeyElement: 
     thekeyElement 
     pprint(thekeyElement) 

    if gelkeyElement: 
     gelkeyElement 
     print(gelkeyElement) 
     sleep(3) 

    parser = html.fromstring(response.page_source,response.current_url) 

    gelato = parser.xpath('//*[@id="locu-medium-container"]/div[1]/div/div[1]/div[2]/div[2]/div[1]/div[1]') 

    for gelatos in gelato: 
     print(gelatos) 

if __name__ == '__main__': 

    parse('http://www.lunarosagelato.com/menu') 

此輸出用於類名CSS選擇和XPath類似元件:

<selenium.webdriver.remote.webelement.WebElement 
    (session="01aab8caa61f2362ef2e5d988619d742", element="0.7957563181681526-1")> 

我想到的文字是牙買加石灰Sorbetto。任何幫助真的會被讚賞。

回答

2

當您打印WebElement時,您可以像其他任何對象一樣獲得其to_string功能。如果要將文本鏈接到它,請使用.text

otherkeyElement = response.find_element_by_class_name('locu-menu-item-name') 
print(otherkeyElement.text) 
+0

非常感謝你,那是我缺少的一塊 –