python selenium如何复制文本?

2024-04-25 10:23:23 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用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”之一。怎样?


Tags: textimportdivbyvaluedriverseleniumjs
3条回答

要选择所需的元素,需要使用find_element_by_xpath(xpath)方法(它将返回与xpath匹配的第一个web元素)或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

试试看

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

for c in content:
   print c.text

使用按xpath查找元素是一个很好的做法,因为如果在路径中找不到任何内容,则内容[0]将为空,但如果使用按xpath查找元素,则路径中找不到任何内容,则会出现错误

您将收到一个错误,因为您正试图调用列表对象上的函数。

您正在使用find_elements返回webelement列表而不是find_element

我不知道你想实现什么,但是如果你想打印所有元素的内容,那么下面的代码应该可以工作。

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

相关问题 更多 >