无法创建适当的选择器来分析某个字符串

2024-04-27 04:53:35 发布

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

我创建了一个选择器来从一些html元素中提取特定的字符串。元素中有两个字符串。使用下面脚本中的选择器,我可以解析这两个脚本,而我希望得到后一个脚本,在本例中是I wanna be scraped alone。如何使用任何选择器为要分析的第一个字符串创建障碍?你知道吗

以下是html元素:

html_elem="""
<a class="expected-content" href="/4570/I-wanna-be-scraped-alone">
    <span class="undesirable-content">I shouldn't be parsed</span>
    I wanna be scraped alone
</a>
"""

我试过:

from lxml.html import fromstring

root = fromstring(html_elem)
for item in root.cssselect(".expected-content"):
    print(item.text_content())

我得到的输出:

 I shouldn't be parsed
 I wanna be scraped alone

预期产量:

I wanna be scraped alone

顺便说一句,我也尝试过root.cssselect(".expected-content:not(.undesirable-content)")这种方法,但它绝对不是正确的方法。任何帮助都将不胜感激。你知道吗


Tags: 字符串脚本元素html选择器rootbecontent
1条回答
网友
1楼 · 发布于 2024-04-27 04:53:35

对于这个问题的具体例子,最好的答案是:

for item in root.cssselect(".expected-content"):
    print(item.tail)

aselement.tail返回最后一个子级之后的文本。但是,如果所需的文本在子节点之前或之间,则这将不起作用。因此,一个更可靠的解决方案是:

item.text_content()根据文件:

Returns the text content of the element, including the text content of its children, with no markup.

所以,如果你不想要孩子们的文本,先删除这些:

from lxml.html import fromstring

html_elem="""
<a class="expected-content" href="/4570/I-wanna-be-scraped-alone">
    <span class="undesirable-content">I shouldn't be parsed</span>
    I wanna be scraped alone
</a>
"""

root = fromstring(html_elem)
for item in root.cssselect(".expected-content"):
    for child in item:
        child.drop_tree()
    print(item.text_content())

请注意,在这个示例中也返回了一些空白,我确信这很容易清除。你知道吗

相关问题 更多 >