【问题标题】:Extract text only from the parent tag with Requests-HTML使用 Requests-HTML 仅从父标签中提取文本
【发布时间】:2020-07-18 00:13:23
【问题描述】:

我想使用 Requests-HTML 仅从父标签中提取文本。 如果我们有这样的html

<td>
    <a href="">There</a> <a href="">are</a> <a href="">some</a> <a href="">links.</a> The text that we are looking for.
<td>

然后

html.find('td', first=True).text

结果

&gt;&gt;&gt; There are some links. The text that we are looking for.

【问题讨论】:

  • 你好格鲁克。我会研究漂亮的汤。

标签: python-3.x html-parsing python-requests-html


【解决方案1】:

您可以使用库直接支持的xpath 表达式

from requests_html import HTML
doc = """<td>
    <a href="">There</a> <a href="">are</a> <a href="">some</a> <a href="">links/</a> The text that we are looking for.
<td>"""
html = HTML(html=doc)
# the list will contain all the whitespaces "between" <a> tags
text_list = html.xpath('//td/text()')
# join the list and strip the whitespaces
print(''.join(text_list).strip())  # The text that we are looking for.

表达式//td/text() 将选择所有td 节点及其文本根文本内容(//td//text() 将选择所有文本内容)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 2021-05-05
    • 2021-10-22
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多