python - 如何获取标签下的文字

标签 python python-3.x selenium dom selenium-webdriver

我正在尝试获取标签下的文字 enter image description here

我尝试了几种不同的选择:

dneyot=driver.find_elements_by_xpath("//*[starts-with(@id, 'popover-')]/text()")
dneyot=driver.find_elements_by_xpath("//*[starts-with(@id, 'popover-')]/b[1]/text()")

我的一段代码:

dneyot=driver.find_elements_by_xpath("//*[starts-with(@id, 'popover-')]/text()")
for spisok in dneyot:
    print("Период показов >3 дней", spisok.text)

更新: 我在浏览器中找到我需要的项目:

//*[starts-with(@id, 'popover-')]/text()[1]

但是报错

    selenium.common.exceptions.InvalidSelectorException:
Message: invalid selector: The result of the xpath expression "//*[starts-with(@id, 'popover-')]/text()[1]" is: [object Text]. It should be an element.

最佳答案

如果你想获得不包括 <b> 的文本节点文本,那么您需要使用以下 XPath:

//div[starts-with(@id, 'popover-')]

这将识别 div 节点,然后使用 find_elements_by_xpath()方法,您可以从 div 节点检索所有文本。试试下面的代码:

elements = driver.find_elements_by_xpath("//div[starts-with(@id, 'popover-')]") 
for element in elements:
    print(element.text)

更新:

我怀疑,上述方法可能不起作用,我们可能无法使用常规方法识别/获取该数据 - 在这种情况下,您需要使用 JavaScriptExecutor 来获取如下数据:

driver = webdriver.Chrome('chromedriver.exe')
driver.get("file:///C:/NotBackedUp/SomeHTML.html")

xPath = "//div[starts-with(@id, 'popover-')]"
elements = driver.find_elements_by_xpath(xPath)
for element in elements:
    lenght = int(driver.execute_script("return arguments[0].childNodes.length;", element));
    for i in range(1, lenght + 1, 1):
        try:
            data = str(driver.execute_script("return arguments[0].childNodes["+str(i)+"].textContent;", element)).strip();
            if data != None and data != '':
                print data
        except:
            print "=> Can't print some data..."

由于您的网站是用英语以外的其他语言编写的,您可能无法打印/获取某些数据。

要获取特定的子节点数据,您需要执行以下操作:

from selenium import webdriver
driver = webdriver.Chrome('chromedriver.exe')
driver.get("file:///C:/NotBackedUp/SomeHTML.html")

xPath = "//div[starts-with(@id, 'popover-')]"
elements = driver.find_elements_by_xpath(xPath)
for element in elements:
    # For print b1 text
    b1Text = driver.execute_script("return arguments[0].childNodes[2].textContent", element);
    print b1Text

    # For printing b2 text
    b2Text = driver.execute_script("return arguments[0].childNodes[6].textContent", element);
    print b2Text

print("=> Done...")

希望对你有帮助

关于python - 如何获取标签下的文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54568588/

相关文章:

python - 使用带有 df.loc == 语句的append() Pandas Python

python - 没有名为 django.views 的模块

python - 无法让我的函数执行任何操作

Python 绑定(bind)到 Selenium Webdriver : ActionChain not executing in PhantomJS

java - 如何使用 Selenium 单击网页上的打印按钮

python - 如何修复负载夹具错误

python - 如何取消缩短 URL?

python-3.x - 删除最小 numpy 数组的 p%

python - NLTK 停用词无法识别句子中的 'i'

python - 试图遍历网页以抓取所有足球运动员的名字,但只得到第一个?