我创建了一个选择器来从一些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)")
这种方法,但它绝对不是正确的方法。任何帮助都将不胜感激。你知道吗
对于这个问题的具体例子,最好的答案是:
as
element.tail
返回最后一个子级之后的文本。但是,如果所需的文本在子节点之前或之间,则这将不起作用。因此,一个更可靠的解决方案是:item.text_content()
根据文件:所以,如果你不想要孩子们的文本,先删除这些:
请注意,在这个示例中也返回了一些空白,我确信这很容易清除。你知道吗
相关问题 更多 >
编程相关推荐