Contains text css selector

Is there any selector for elements containing certain text in CSS?

In CSS, selectors are used to select an HTML element to style. There are various CSS selectors available in CSS, such as class selector, id selector, name selector, etc.

Sometimes, developers need to select an HTML element based on the custom attribute value instead of selecting it based on the class name or id. We can use the attribute-value CSS selector to select the HTML element based on the particular attribute value. We can also add the custom attribute instead of only pre-defined attributes in HTML.

Syntax

Users can follow the syntax below to use the attribute-value CSS selector to select elements containing certain text.

[attribute name="attribute value"] < /* CSS code */ >

In the above syntax, the attribute name can be the name of the attribute that HTML element contains, and you want to select an element based on attribute value. The attribute value is a value of the particular attribute.

Example 1

We have created the ‘social’ div element in the example below. In the div element, we have added the child div elements containing the ‘app_name’ attribute and its value. In CSS, we used the ‘app_name’ as an attribute name and different values to select different div elements.

In the output, users can observe that it has styled the div elements containing the ‘Facebook’ and ‘Instagram’ attribute value.

   [app_name="facebook"] < background-color: #3b5998; color: white; >[app_name="instagram"]  

Using the [attribute=value] CSS selector to target an element based on its attribute value

facebook
twitter
instagram
youtube

Example 2

In the example below, we have used the attribute-value selector, but we have used the ‘~’ sign for the partial selector. It selects the HTML element, even if the attribute contains a particular word in a value, rather than matching the whole word in the first example.

We used the ‘app’ word in the attribute-value CSS selector here. So, it will select all HTML elements whose type attribute contains the ‘app’ word. The output shows that it has styled the first three div elements as it contains the app word.

   [type~="app"]  

Using the [attribute~=value] CSS selector to target an element based on its attribute value

Web application
Mobile application
Desktop application
Anroid device

Example 3

We used the ‘^’ sign with the attribute-value CSS selector in the example below. It allows the selection of all elements whose attribute value starts with a particular word.

Here, we have created the div elements with different class names. In CSS, we use the attribute-value selector to select all HTML elements whose class name starts with the ‘a’ character.

   [class ^="a"]  

Using the [attribute*=value] CSS selector to target an element based on its attribute value

ABC
ADE
BCD
CDE

Example 4

In the example below, we created the table containing the snack’s name, expiry date, and price. Also, we added a status equal to expired for the expired snacks. We selected the ‘expired’ snacks in CSS and styled them using the attribute-value CSS selector.

   td[status*=expired]  

Using the [attribute*=value] CSS selector to target an element based on its attribute value

Snack Expiry Price
Chips 01/01/2024 20 INR
Chocolate 01/09/2023 30 INR
Candy 01/01/2022 25 INR

Users learned to select an HTML element based on a certain text. We can add custom attributes to the HTML element, and after that, we can use the attribute-value CSS selector to select elements based on the attribute value.

Читайте также:  Mousemove event in javascript

Источник

A way to match on text using CSS locators

So I use xpath locators and slowly converting to CSS.
I haven’t found a way to do an exact match based on text. For example converting //a[text()=’Log Out’] . I know you can do css=a:contains(‘Log Out’) but I want to match exactly to the text. Also I know I can do link=Log Out but looking for a solution with CSS.

6 Answers 6

css=a[text='Log Out'] or a[innertext='Log Out'] 

Can you please try this one out?

Or if that doesn’t work and you still don’t want to use xpath because it’s slow, you can always try: link=Log Out . That’s still better then xpath.

So i found a possible solution for you mate. If you are trying to find an exact String you could always use Regular expression like this:

Just replace div with a and there you go. This will find ONLY AB in whatever text div it looks for. OFC if you have more then one links with text AB (which is a bad thing 😛 ) then it will find them all..

Try this and see if it helps. 🙂

Neither of those work unfortunately. I know I can use link=Log Out but just seeing if there was a solution in CSS.

Sorry to hear that 🙁 Unfortunately I don’t think CSS has match exact param. But I might be mistaken. Hope you find an answer soon mate. 🙂 Cheers.

:contains() is not part of the current CSS3 specification so it will not work on all browsers, only ones that implemented it before it was pulled. (see w3.org/TR/css3-selectors)

This is a nice place for a few CSS selectors.

Thought it might be useful for people following this thread.

For those who are looking to do Selenium css text selections this script might be of some use

Trick is to select parent of element of one that you are looking for and then search for child that has the text.

public static IWebElement FindByText(this IWebDriver driver, string text) < var list = driver.FindElement(By.CssSelector("#RiskAddressList")); var element = ((IJavaScriptExecutor)driver).ExecuteScript(string.Format(" var x = $(arguments[0]).find(\":contains('')\"); return x;", text), list); return ((System.Collections.ObjectModel.ReadOnlyCollection)element)[0]; > 

this will return first element if there is more than one since it’s always one element in my case.

As per the following discussions:

The :contains pseudo-class isn’t in the CSS Spec and is not supported by either Firefox or Chrome (even outside WebDriver).

Python based solution

To locate the element with text as Log Out you can use either of the following Locator Strategies:

element = driver.find_element(By.LINK_TEXT, "Log Out") 
element = driver.find_element(By.XPATH, "//a[text()='Log Out']") 

Ideally, to locate the element you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.LINK_TEXT, "Log Out"))) 
element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[text()='Log Out']"))) 
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC 

Java based solution

To identify the element with text as Log Out you can use either of the following Locator Strategies:

WebElement element = driver.findElement(By.linkText("Log Out")); 
WebElement element = driver.findElement(By.xpath("//a[text()='Log Out']")); 

Ideally, to identify the element you need to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:

WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Log Out"))); 
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[text()='Log Out']"))); 

References

You can find a couple of relevant detailed discussions in:

Читайте также:  Php where value in array

Источник

Top 5 CSS Selectors You Need to Know.

Scraping might get hard at times when you’re dealing with website structures that frequently change or in general, are hard to scrape with just the point-and-click interface. No need to stress, with the knowledge of the CSS selector — any website structure can be overcome and any website — scraped. Here are the TOP 5 CSS selectors that we frequently use and might be of great use to you.

First and foremost — when creating selectors, you might have noticed that in the drop-down menu of selectors there is no such “CSS selector” listed. This is because the CSS selector is always working and visible. It is the log that, when elements are selected from a web page, shows as the HTML parts of the elements selected.

Web Scraper uses CSS selectors to find HTML elements on the designated website. When elements are selected, the CSS selector makes a best guess of what the selected elements might be, and what to extract from them. This is where the flexibility of designing specific CSS selectors in different situations comes in.

First — «:contains»

For example, in a situation when specific categories are needed, but the selector selects the whole log of categories. The «:contains» selector will recognize the specific text you are looking to retrieve.

contains-selector-not-in-use-example-selecting-all-categories-Web-Scraper-Blog

To select only, for example, the categories of “Tops”, “Dresses”, and “Jeans”, we have to custom-write the CSS selector.

To the selected “[aria-hidden] a”, we add a colon, and with “contains(“Tops”)” we designate the selector to select the specific category which contains the string “Tops”. Now add the same to designate also the dresses and jeans categories and that’s it — a link selector, which only will select the 3 specific categories has been created.

contains-selector-in-use-specific-categories-selected-Web-Scraper-Blog

Second — «:not(:contains)»

However, for situations where all listings are necessary except for listings that contain a specific characteristic, most commonly seen when scraping product pages, the «:not(:contains)» comes in use. Exactly as the «:contains» selector it works for text-related strings.

not-contains-selector-not-in-use-derive-categories-Web-Scraper-Blog

For example, all dresses are of interest except for the ones that are knitted. To exclude that specific characteristic, we take the CSS selector that was created when selecting the elements, and add the “:not(:contains(“Knit”))” equation. Similar to the CSS selector we created for the specific categories; however, with the “not” part the selector is designated to collect all except for the specific.

Читайте также:  Java decompiler and android

not-contains-selector-in-use-derived-particular-characteristic-Web-Scraper-Blog

Third — «>»

Diving deeper into the possibilities of creating custom CSS selectors — we have the “greater than “>”” symbol selector. It selects the direct “child” element of your chosen selector.

To better explain — this is how the CSS selector has guessed the elements we are looking to retrieve from selecting them with the point-and-click interface.

For this current version of the website, it will work and retrieve the necessary price points selected; however, with the “>” selector we can adjust the scraper to be more precise when selecting the elements. This can come in handy when selecting elements containing an attribute that can be found in multiple positions within the site. This will ensure that the scraper will only extract the value, which positionally follows this particular structure.

To better explain what it really does, let’s take a look at the websites HTML elements.

Now, the written CSS selector will be working as it will look at the “product-item”, search two positions down from there to the “item-details” and one position lower to retrieve the “item-price”.

However, in this situation, for this specific website, we see that there is an even shorter, more precise, and flexible way of retrieving the prices of the items which would decrease the chance of the selector to break when the structure of the website is altered.

simpler-selector-selecting-prices-css-selector-Web-Scraper-Blog

On some websites, it would require longer strings of the CSS selector — all depends on the layout of the website’s elements.

Fourth — «:has»

This selector is specifically for finding attributes inside an element. For example, on our chosen website, we want to retrieve dresses which are in black or one of the available colors is black.

has-css-selector-selecting-attributes-of-elements-Web-Scraper-BLog

With just point-and-click, it would not be possible to select this specific character attribute of the item elements; therefore, this is a very useful and crucial selector for precise scraping.

Fifth — «~»

The “~” selector selects all the elements after a specific one if they are in the same structural level. For example, when selecting the characteristics of a product — we select the main element and with the “~” specify that all the elements positioned next to it have to be retrieved.

~-wave-selector-in-use-Web-Scraper-Blog

These are the most primary and most used by our team. The main takeaway is that creating custom CSS selectors will decrease the chances of the sitemap breaking whenever there are any changes applied to the website; however, it takes time to examine and figure out which selector is the best case for the specific layout of the website and the specific data that is needed to be retrieved.

There are more possibilities and variations of CSS selector for more advanced and specified scraping necessities; however, the two mentioned in this blog might be very useful for not only advanced-level scrapers but also very important for beginner-level.

For more information and details of other CSS selectors, you might be interested in checking CSS selector documentations:

Источник

Оцените статью