【问题标题】:Python not returning the text from the H3 tagPython没有从H3标签返回文本
【发布时间】:2020-03-03 14:33:40
【问题描述】:

我正在查看的结构如下

<div id="historyContainer">
    <div class id="offerHistory">
        <div class="theTitle">…</div>
        <br>
        <p>…</p>
        <br>
        <h3>Title</h3>
    </div>
</div>

这是我的 Python

offerHistory = browser.find_element_by_id('offerHistory')
title = offerHistory.find_elements_by_tag_name('h3')
print(title)

这是打印出来的

[<selenium.webdriver.remote.webelement.WebElement (session="d7aef4eab17ec32e0280c1177b5016d9", element="eaf8e28e-9620-4e94-81a8-f7e13edc2c48")>]

如何打印“标题”?

【问题讨论】:

  • 返回值是一个列表,所以如果你只想要第一个(因为你知道你只有一个):print(title[0].text) 应该可以工作
  • @chatterone 我的索引超出范围
  • 如果索引越界,那么输出不是你得到的,因为它显示了一个列表[&lt;selenium...&gt;]

标签: python selenium selenium-webdriver


【解决方案1】:

添加“.text”:

title = browser.find_elements_by_tag_name('h3')
print(title.text)

【讨论】:

  • 这样做时出现错误。属性错误,列表对象没有属性“文本”
  • 不理想,因为 h3 在这个特定的块中。
  • 如果我理解正确find_elements_by_tag_name 返回一个列表。为了使此代码正常工作,您必须遍历 title 或使用 dict 理解。 print([t.text for t in title])
  • @denys.halenok 这会打印出 [u'Hello World']。如果我执行 t.text[0],它将打印出 [u'H']。我怎样才能让它只打印 Hello World?
  • @soldfor 试试这个:for t in title: print(t.text)
【解决方案2】:

你很亲密。在&lt;div class id="offerHistory"&gt; 父节点内:

<div class id="offerHistory">
    <div class="theTitle">…</div>
    <br>
    <p>…</p>
    <br>
    <h3>Title</h3>
</div>

只有一个&lt;h3&gt;标签被正确返回:

title = offerHistory.find_elements_by_tag_name('h3')

所以当你print(title) 时,元素打印为:

[<selenium.webdriver.remote.webelement.WebElement (session="d7aef4eab17ec32e0280c1177b5016d9", element="eaf8e28e-9620-4e94-81a8-f7e13edc2c48")>]

在您的用例中,您希望从 &lt;h3&gt; 节点中提取文本 Title,您可以使用以下任一 Locator Strategies

  • 使用css_selectorget_attribute()

    print(driver.find_element_by_css_selector("div#offerHistory h3").get_attribute("innerHTML"))
    
  • 使用xpathtext属性:

    print(driver.find_element_by_xpath("//div[@id='offerHistory']//h3").text)
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 2018-04-06
    • 1970-01-01
    相关资源
    最近更新 更多