'python selenium how to copy text?
How to copy text with selenium xpath? When I writing
driver.find_elements_by_xpath("//div[@class='rankingItem-value js-countable']").text
I get next error:
Traceback (most recent call last):
File "<stdin>", line 15, in <module>
AttributeError: 'list' object has no attribute 'text'
full code:
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)
I need to copy site's global rank to a table, "22" one. How?
Solution 1:[1]
To select required element you need to use find_element_by_xpath(xpath)
method (that will return first web-element matched by xpath
) or find_elements_by_xpath(xpath)[0]
(that will return first web-element from list of elements matched by xpath
). Also your XPath
is incorrect as there is no div
with class="rankingItem-value js-countable"
- you need span
instead. So try following:
content = driver.find_element_by_xpath('//span[@class="rankingItem-value js-countable"]').text
or
content = driver.find_elements_by_xpath('//span[@class="rankingItem-value js-countable"]')[0].text
If you need to get "Country rank" or "Category rank", use below:
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
Solution 2:[2]
Try
content = driver.find_elements_by_xpath("//div[@class='rankingItem-value js-countable']")
for c in content:
print c.text
It's a good practice to use find_elements_by_xpath because if you find nothing in the path, content[0] will be empty, but if you use find_element_by_xpath and you find nothing in the path, you will get an error
Solution 3:[3]
You are getting an error because you are trying to call the function on the list object.
You are using find_elements which returns a list of web elements and not find_element
I am not sure what you are trying to achieve but if you trying to print the content of all the elements then the following code should work.
elements = driver.find_elements_by_xpath("//div[@class='rankingItem-value js-countable']")
content = "".join([element.text for element in elements])
print(content)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Andersson |
Solution 2 | parik |
Solution 3 | ash |