"Using the CSS :nth-of-type selector in a for loop does not pull out the

I am looking to extract the strings text_i_wantA, text_i_wantB, and text_i_wantC from each of the 3 children within each of the 10 div class = col-12. To enhance readability, I have only included two similarly structured divs here. If the output does not currently include the actual .content[0], I can always parse that later.

Below is the complete code:

title,date,name,number = [],[],[],[]
while True:
    soup = bs(driver.page_source, 'html5lib')
    for div in soup.find_all('a', attrs={'title':'ad i'}):
        titl = div.get_text(strip=True)
        title.append(titl)
    else:
        break
    for col in soup.find_all('div', attrs={'class':'col-12'})[1::2]:
        row = []
        for entry in col.select('div.row div'):
            target = entry.find_all(text=True, recursive=False)
            row.append(target[0].strip())
        name.append(row[0])
        date.append(row[1])
        number.append(row[2])  

    next_btn = driver.find_elements_by_css_selector(".page-next button")
    if next_btn:
        actions = ActionChains(driver)
        actions.move_to_element(next_btn[0]).click().perform()
        time.sleep(4)
    else:
        break
driver.close()

Expected results are as follows:

title = ["text_i_already_have1", "text_i_already_have2", ...]

date = ["text_i_wantA", "text_i_wantAA", ...]

name = ["text_i_wantB", "text_i_wantBB", ...]

number = ["text_i_wantC", "text_i_wantCC", ...]

Issue: The current output when using slice [1::2]

title = ["text_i_already_have1", "text_i_already_have2", ...]
date = ['text_i_wantA', 'text_i_wantAA', ...],
name = ['', '', '', '', '', '', '', '', '', '']
number = ['', '', '', '', '', '', '', '', '', '']

Is the problem related to my CSS selection or the loop itself?

The first line works properly:

print(soup.find_all('div', attrs={'class':'col-12'}))
without a slice gives me a list of the div elements containing the strings I want to extract (text_i_want):

... (omitted for brevity) ...

The unwanted string text_i_dont_want is consistently found inside the

<span class="processlink">
element, which is always the last child within one of the 3
<div class="row">
elements contained within each of the 10 
<div class="col-12">
.

Answer №1

If I grasp your meaning correctly now, implementing this code should guide you in the right direction (or at least a step closer):

surface,material,size = [],[],[]
for element in page.find_all('div', attrs={'class':'container'}):
    data = []
    for item in element.select('div.item div'):
        info = item.find_all(text=True, recursive=False)
        data.append(info[0].strip())
    surface.append(data[0])
    material.append(data[1])
    size.append(data[2])   

When you run print(size), expect to see something like:

['info_you_needA', 'info_you_needAA']

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporate Margins for Table Cells in Outlook (HTML Email)

I'm currently in the process of creating an email newsletter and testing it out on Litmus. Here's how the newsletter design should appear (refer to the image below): Although I understand that it may not look exactly the same on Outlook, is the ...

Adjusting the equivalence value within an if statement

Check out my code snippet: com=input('> ') while True: if com=='say': print('1') com=input('> ') if com=='change': global change_com change_com=input('Cha ...

pymysql transaction successfully saves a single insert query, while choosing to overlook two update queries without triggering any errors

Trying to set up the save method of a PyQt5 form with a pymysql transaction, I am facing an issue. The save process involves one insert query for a new record and two updates that should follow the insert. However, even though the method runs smoothly with ...

Trigger file upload window to open upon clicking a div using jQuery

I utilize (CSS 2.1 and jQuery) to customize file inputs. Everything is working well up until now. Check out this example: File Input Demo If you are using Firefox, everything is functioning properly. However, with Chrome, there seems to be an issue se ...

Creating a responsive Select tag

Currently developing a responsive webpage using HTML5 and CSS3. Within the HTML is a form with a table that collapses as the page size decreases. However, encountering an issue where the select tag does not collapse alongside other elements in the form. Be ...

Is there a way to extract and exhibit the text from an image using Python?

Could someone assist me in extracting only the text within the highlighted red area? I have been experimenting with Python but haven't been successful in achieving this. My goal is to create a script that prompts for an address, then opens Firefox (or ...

I'm looking to generate a dictionary that includes each element from a list as a key and all other elements from the list as the corresponding value

Is there a clever way to create a dictionary in Python where each key is an element from a list, and the corresponding value contains all elements from the list except that key? Consider this example: If I had lst = [1, 2, 3, 4, 5, 6] How can I use ...

Display a floating label above the text input when it is focused or when it holds text

I am trying to create an animated search bar where the label moves from being over the text input to above it. I came across a helpful example in a fireship.io video, which includes the CSS and HTML code available here The example I found demonstrates the ...

Customize the Carousel navigation arrows in Bootstrap 3

Greetings everyone, I am currently utilizing Bootstrap's Carousel options and I am looking to change the appearance of the arrows as I find them unattractive. My desired look for the arrows is as follows: https://i.sstatic.net/Rz9Mb.png However, I ...

Demonstration of how to use mpatches for a matplotlib legend guide not functioning as

When attempting to run the code example provided here and available for download here in Python 3, I encounter an issue: import matplotlib.patches as mpatches import matplotlib.pyplot as plt red_patch = mpatches.Patch(color='red', label='T ...

Utilize CSS to format the output of a script embedded within

When I embed the following script in my HTML, the output doesn't have any styling. How can I style the script output to blend well with the existing HTML structure? I tried accessing the output by ID, but couldn't figure it out. <script> ...

Can you point me in the direction of some resources for developing a custom plugin with stylelint?

After visiting the stylelint website and github, I downloaded it locally using npm. The stylelint website suggests using the following format to create my own plugin: var myPluginRule = stylelint.createPlugin(ruleName, function(primaryOption, secondaryOpt ...

What could be causing the CSS transforms to not show up on the page?

Can't seem to get my navigation panel to slide in when the nav button in the main menu is clicked. I've done this before without issues, so not sure what's up. Any help? Custom HTML Code <!-- Header --> <div class="header"> & ...

Send responses to contact information via email

My website is being developed on repl.it, using their HTML/CSS/JS server which doesn't support PHP. This poses a challenge as I need PHP for submitting contact responses via email. Is there an alternative solution using Node.js that would allow me to ...

How can I use JQuery to select an element with a style attribute in Internet Explorer?

When using JQuery, I have set my target to be the following: <li style="margin-left: 15px;">blah<li> I am using this code to achieve that: $(".block-category-navigation li[style='margin-left: 15px;']").addClass('sub-menu' ...

Tips for ensuring that content doesn't shift down when clicking a drop-down menu

I currently have three dropdowns that function as an accordion. When I click on one dropdown, the rest of the content below shifts down, which is not the behavior I want. Is there a way to prevent the content below each dropdown from moving when a dropdow ...

Vanilla JS method for resetting Bootstrap 5 client-side validation when focused

I'm currently exploring Bootstrap 5's client-side validation feature. However, I've encountered a usability issue with the is-invalid class. After clicking the submit button, this class persists until the correct input is entered. I would li ...

Struggling to design a functional mobile keyboard

I've been working on creating a mobile keyboard, but I'm facing some issues with the JavaScript part. The problem seems to be in my code as the keyboard isn't responding when I try to type. Here's a snippet of the JavaScript I'm us ...

How can the style of a div's :after pseudo-element be modified when hovering over its :before pseudo-element?

Here is some CSS code: .myDiv:before{ content:''; width:15px; height:15px; display:block; } .myDiv:after{ ... ... display:none; } And here is the corresponding HTML code: <div class='myDiv'></div> ...

Guide on setting a personalized color for progress bars in Bootstrap 4

I'm working on a progress bar: <div class="progress"><div class="progress-bar" style="width:{{a.49}}%">{{a.49}} %</div> </div> Is there a way to apply a custom color to the progress bar based on a condition in CSS? : If a.49 ...