如何使用selenium xpath复制文本? 当我写作的时候
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”之一。怎样?
要选择所需的元素,需要使用
find_element_by_xpath(xpath)
方法(它将返回与xpath
匹配的第一个web元素)或find_elements_by_xpath(xpath)[0]
(它将返回与xpath
匹配的元素列表中的第一个web元素)。你的XPath
也不正确,因为没有div
与class="rankingItem-value js-countable"
-你需要span
代替。因此,请尝试以下操作:或者
如果您需要获得“国家排名”或“类别排名”,请使用以下内容:
试试看
使用按xpath查找元素是一个很好的做法,因为如果在路径中找不到任何内容,则内容[0]将为空,但如果使用按xpath查找元素,则路径中找不到任何内容,则会出现错误
您将收到一个错误,因为您正试图调用列表对象上的函数。
您正在使用find_elements返回webelement列表而不是find_element
我不知道你想实现什么,但是如果你想打印所有元素的内容,那么下面的代码应该可以工作。
相关问题 更多 >
编程相关推荐