Python BeautifulSoup give multiple tags to findAll

PythonBeautifulsoup

Python Problem Overview


I'm looking for a way to use findAll to get two tags, in the order they appear on the page.

Currently I have:

import requests
import BeautifulSoup

def get_soup(url):
    request = requests.get(url)
    page = request.text
    soup = BeautifulSoup(page)
    get_tags = soup.findAll('hr' and 'strong')
    for each in get_tags:
        print each

If I use that on a page with only 'em' or 'strong' in it then it will get me all of those tags, if I use on one with both it will get 'strong' tags.

Is there a way to do this? My main concern is preserving the order in which the tags are found.

Python Solutions


Solution 1 - Python

You could pass a list, to find any of the given tags:

tags = soup.find_all(['hr', 'strong'])

Solution 2 - Python

Use regular expressions:

import re
get_tags = soup.findAll(re.compile(r'(hr|strong)'))

The expression r'(hr|strong)' will find either hr tags or strong tags.

Solution 3 - Python

To find multiple tags, you can use the , CSS selector, where you can specify multiple tags separated by a comma ,.

To use a CSS selector, use the .select_one() method instead of .find(), or .select() instead of .find_all().

For example, to select all <hr> and strong tags, separate the tags with a ,:

tags = soup.select('hr, strong')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDasSnipezView Question on Stackoverflow
Solution 1 - PythonjfsView Answer on Stackoverflow
Solution 2 - PythonTerryAView Answer on Stackoverflow
Solution 3 - PythonMendelGView Answer on Stackoverflow