简体   繁体   English

在dom scrape中寻找子元素的选择器

[英]Seeking a selector for child elements in dom scrape

I am unable to change any html on the website in question. 我无法更改相关网站上的任何html。

Here is some html: 这是一些HTML:

<ul id="utility-menu" class="menu menu--primary">

        <li><a class="" href="https://www.example.com/newsstand" target="_blank">Magazines</a></li>

        <li><a class="" href="https://secure.bla.com/example/promo/GiveAGift/" target="_blank">Gifts</a></li>

        <li>

          <a href="/email_check?lang=fr">Français</a>
        </li>

            <li><a class="" href="/signin">Sign In</a></li>

        <li>
          <div class="i-am-canadian">
            <img alt="Canadian flag" height="23px;" src="https://secure.example.com/assets/images/icons/ui/i-canadian-c8a132ad64588dcc0b2e61cc589dfef3.png" width="40px;">
          </div>
        </li>
      </ul>

I managed to select the menu using: 我设法使用以下方法选择菜单:

document.querySelectorAll('.menu--primary')[0]

The element I'm interested in is: 我感兴趣的元素是:

<a href="/email_check?lang=fr">Français</a>

This element ia language selection for the site visitor that will be either "English" or "Français". 该元素是网站访问者的语言选择,将是“英语”或“法语”。

If the user is on an English language page the value of the element will be that shown. 如果用户在英语页面上,则该元素的值将显示。 But if they are on the French language equivalent the element will be <a href="/email_check?lang=en">English</a> 但是,如果使用等效的法语,则该元素将为<a href="/email_check?lang=en">English</a>

I would like a selector that returns either "English" or "Français". 我想要一个返回“英语”或“法语”的选择器。

How would I do that? 我该怎么办?

Answer: 回答:

var el = document.querySelector('#utility-menu a[href^="/email_check?lang="').textContent;

It will select first a element with attribute href begining with /email_check?lang= in #utility-menu . 它将首先在#utility-menu选择一个属性href/email_check?lang= a元素。 Probably you can .trim() text to get rid of whitespaces. 可能您可以使用.trim()文本来消除空格。

If your html is not going to change much, you can use 如果您的html不会有太大变化,则可以使用

var test = document.querySelector("ul > li > a[href='/email_check?lang=fr']");

console.log(test.textContent); // Français

https://jsfiddle.net/u4vjq8ah/ https://jsfiddle.net/u4vjq8ah/

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

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