views:

43

answers:

3

I know how to pass 1 attribute, but how do I pass 2?

e.g.

somerows = soup.findAll('a', target="blank")

what if I want all links that have target="blank" and class="blah" ?

A: 

If you want a more complicated search, you can also do:

key = lambda tag: ...
# or even
def key( tag )
    return len( tag.attrs ) == 2 # for example

soup.findAll( key )

See the docs.

katrielalex
This raises a SyntaxError.
Aaron Gallagher
It does indeed. Fixed.
katrielalex
+2  A: 

You can use a dictionary to avoid having problems with some attribute names such as 'class':

soup.findAll('a', {
    "target" : "blank",
    "class" : "blah",
    "href" : re.compile(...)
})

This is mentioned in the documentation.

Mark Byers
in one of the attributes, I am using: href=re.compile('...') how can this fit into what you posted?
Blankman
See my answer instead.
Aaron Gallagher
+1  A: 

soup.findAll('a', 'blah', target='blank', href=re.compile(...))

Quoth the BS docs:

The attrs argument would be a pretty obscure feature were it not for one thing: CSS. It's very useful to search for a tag that has a certain CSS class, but the name of the CSS attribute, class, is also a Python reserved word.

You could search by CSS class with soup.find("tagName", { "class" : "cssClass" }), but that's a lot of code for such a common operation. Instead, you can pass a string for attrs instead of a dictionary. The string will be used to restrict the CSS class.

Aaron Gallagher
Uh, what's with the downvote?
Aaron Gallagher
so just comma seperated? hmm..let me try.
Blankman