0

如何从以下元素中获取“关注者”类别下的所有名称。名字的排列方式对我来说有点陌生,这就是为什么我无法得到所有这些。我已经使用了一个能够抓取第一个的选择器。但是,我希望所有名称都在“Followed by”标题下,直到“edited_into”标题。提前致谢。

这是所需名称所在元素的链接: https ://www.dropbox.com/s/nzmvfc75szlgyyn/elements%20for%20expression.txt?dl=0

我试过的选择器:

a#followed_by+h4.li_group+div.odd a

我得到的结果只是名字:

Star Trek V: The Final Frontier

顺便说一句,我唯一的目的是使用此选择器解析名称而不是样式。

4

1 回答 1

1

您拥有的选择器几乎是正确的。

a#followed_by+h4.li_group ~ div.soda a

与它的~工作方式不同的+是,它将选择选择器第一部分之后的任何匹配元素,而+只会选择紧随选择器第一部分之后的元素。当然,我指的是“第一部分” a#followed_by+h4.li_group

我还将选择器更改为查找,div.soda而不是div.odd让您获得所有相关元素,而不仅仅是奇怪的元素。


由于 CSS 选择器的工作方式,我们不能要求“只有元素直到edited_into”。但是,我们可以使用 JavaScript 解决这个问题。

for带有条件的简单循环break将是最简单的方法。

var titles = [];
var items = document.querySelectorAll('a#followed_by+h4.li_group ~ div.soda a');
//firstEditedIntoItem represents the first element in
//the `edited_into` section. If it's null, then there
//is none, and we have nothing to worry about.
var firstEditedIntoItem = 
    document.querySelector
    ('a#edited_into+h4.li_group+div.soda a, a#spin_off_from+h4.li_group+div.soda a');
    //   Note: This selector will find the first instance that matches any of the
    //   specified sections. You could add another and replace `spin_off_from` with
    //   another section id.
for(var i=0; i<items.length; i++) {
    var it = items[i];
    //don't accept elements after 'edited_into'
    // If firstEditedIntoItem is null, it will not match either.
    if(it==firstEditedIntoItem) break;
    titles.push(it.textContent);
}
console.info(titles.join('\n'));
于 2017-08-30T00:04:03.663 回答