2017-01-16 36 views
2

如何用硒xpath複製文本? 當我寫python硒如何複製文本?

driver.find_elements_by_xpath("//div[@class='rankingItem-value js-countable']").text 

我得到一個錯誤:

Traceback (most recent call last): 
    File "<stdin>", line 15, in <module> 
AttributeError: 'list' object has no attribute 'text' 

全碼:

from selenium import webdriver 
from selenium.webdriver.common.keys import Keys 
import time 
driver = webdriver.Firefox() 
driver.get('https://www.similarweb.com/') 
driver.find_element_by_id("js-swSearch-input").send_keys("www.pornhub.com") 
driver.find_element_by_css_selector("button.swSearch-submit").click() 
#self.driver.implicitly_wait(30) 
time.sleep(10) 


content = driver.find_elements_by_xpath("//div[@class='rankingItem-value js-countable']").text 
print(content) 

我需要網站的全球排名複製到表中, 「22」 之一。怎麼樣?

+0

'find_elements_by_xpath'返回列表元素。您必須迭代元素並從每個元素中檢索文本。 –

+0

可能的重複[如何使用Selenium Python xpath選擇元素](http://stackoverflow.com/questions/19035186/how-to-select-element-with-selenium-python-xpath) – parik

回答

1

要選擇需要的元素,你需要使用find_element_by_xpath(xpath)方法(這將返回第一個web元素匹配xpath)或find_elements_by_xpath(xpath)[0](這將返回匹配xpath匹配的元素列表中的第一個web元素)。 XPath也是不正確的,因爲沒有divclass="rankingItem-value js-countable" - 你需要span來代替。因此,嘗試以下操作:

content = driver.find_element_by_xpath('//span[@class="rankingItem-value js-countable"]').text 

content = driver.find_elements_by_xpath('//span[@class="rankingItem-value js-countable"]')[0].text 

如果您需要獲得 「國家排名」 或 「分類等級」,下面用:

content_of_country_rank = driver.find_elements_by_xpath('//span[@class="rankingItem-value js-countable"]')[1].text 
content_of_category_rank = driver.find_elements_by_xpath('//span[@class="rankingItem-value js-countable"]')[2].text 
+0

謝謝,它的工作原理!此外,非常感謝類別排名選項。 –

0

您正在嘗試調用列表對象上的函數時出現錯誤。

您正在使用find_element 小號返回webelements的列表,而不是find_element

我不知道你想達到什麼樣的,但如果你想打印的所有元素的內容,然後下面的代碼應該工作。

elements = driver.find_elements_by_xpath("//div[@class='rankingItem-value js-countable']") 
content = "".join([element.text for element in elements]) 
print(content) 
0

嘗試

content = driver.find_elements_by_xpath("//div[@class='rankingItem-value js-countable']") 

for c in content: 
    print c.text 

這是一個很好的做法是使用find_elements_by_xpath,因爲如果你發現在路徑沒什麼,內容[0]將是空的,但如果你使用find_element_by_xpath和你在路徑中找不到任何東西,你會得到一個錯誤