简体   繁体   English

如何使用 CSS 选择器划分 div 元素的内容?

[英]How can I divide a div element's content with CSS selector?

Let's say i have something like that:假设我有这样的事情:

<div class="c1">
    BlahBlahBlah Some text that I want to fetch.
    <br/>
    <div class="c2">something does not important.</div>
    <a href="blabla.html">a link text</a>
</div>

I want to fetch just "BlahBlahBlah Some text that I want to fetch."我只想获取“BlahBlahBlah 我想获取的一些文本”。 text.文本。 When I use "div.c1" css selector, It gives "BlahBlahBlah Some text that I want to fetch. something does not important. a link text."当我使用“div.c1”css选择器时,它给出了“BlahBlahBlah我想要获取的一些文本。一些不重要的东西。一个链接文本。”

How can I fetch the text that I want?如何获取我想要的文本? (Note: HTML code does not contain any mistake, please do not suggest modification, it is certainly as I wrote. The site that I want to fetch text does not belong to me, so I can not change the code.) (注:HTML代码不包含任何错误,请不要建议修改,肯定是我写的。我要提取文本的站点不属于我,所以我无法更改代码。)

Simple answer.简单的回答。 You can't.你不能。 CSS selectors target Nodes, not specific letters in some text. CSS 选择器针对节点,而不是某些文本中的特定字母。 There are small exceptions when you consider pseudo selectors, but you can't accomplish what you want with CSS alone.考虑伪选择器时有一些小例外,但仅靠 CSS 无法实现您想要的效果。

The best advice I have is to modify the HTML and wrap the content you want to target in a <span> element and give it a CSS class that you can actually target.我的最佳建议是修改 HTML 并将您想要定位的内容包装在<span>元素中,并为其提供一个您可以实际定位的 CSS 类。

Edit : (Since finding out you can't modify the page and you're using Jsoup to fetch it.)编辑:(自从发现您无法修改页面并且您正在使用 Jsoup 来获取它。)

Since you're using Jsoup to fetch the page and target your Node you simply have one more step to grab your text.由于您使用 Jsoup 来获取页面并定位您的节点,因此您只需再执行一步即可获取文本。 Basically, after you select your node and grab the inner text, just run a regex over it and grab everything before the first period.基本上,在您选择节点并获取内部文本后,只需在其上运行正则表达式并在第一个周期之前获取所有内容。

Your regex should look something like this in Java: "(.*\\\\.)"你的正则表达式在 Java 中应该是这样的: "(.*\\\\.)"

You can "fetch" the text you want, assuming you mean "select" it for purposes of applying CSS rules, by writing a rule for the top-level element, and then overriding it for the children:你可以“获取”你想要的文本,假设你的意思是“选择”它是为了应用 CSS 规则,通过为顶级元素编写规则,然后为子元素覆盖它:

.c1   { color: rebeccapurple; }
.c1 * ( color: initial; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM