python selenium 如何复制文本?

新手上路,请多包涵

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

原文由 Nia Grace 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 599
2 个回答

要选择所需的元素,您需要使用 find_element_by_xpath(xpath) 方法(这将返回与 xpath 匹配的第一个网络元素)或 find_elements_by_xpath(xpath)[0] 匹配的第一个网络元素(该网络元素将首先返回–来自 xpath 匹配的元素列表)。另外你的 XPath 是不正确的,因为没有 divclass="rankingItem-value js-countable" 你需要 span -ff.eada-5.所以尝试以下:

 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

原文由 Andersson 发布,翻译遵循 CC BY-SA 3.0 许可协议

尝试

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

for c in content:
   print c.text

使用 find_elements_by_xpath 是一个很好的做法,因为如果您在路径中找不到任何内容,content[0] 将为空,但是如果您使用 find_element_by_xpath 而您在路径中找不到任何内容,则会出现错误

原文由 parik 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题