Finding inline style with lxml.cssselector
New in this library (unfortunately no longer familiar with BeautifulSoup) trying to do something very simple (search inline style):
<td style="padding: 20px">blah blah </td>
I just want to select all tds where style = "padding: 20px" but I can't figure it out. All examples show how to select td, for example:
for col in page.cssselect('td'):
but that doesn't help me much.
+2
source to share
3 answers
Please note that Ruslan Spivak and nosklo gave better quality answers below.
import lxml.html
data = """<td style="padding: 20px">blah blah </td>
<td style="padding: 21px">bow bow</td>
<td style="padding: 20px">buh buh</td>
"""
doc = lxml.html.document_fromstring(data)
for col in doc.cssselect('td'):
style = col.attrib['style']
if style=='padding: 20px':
print(col.text.strip())
prints
blah blah
buh buh
and manage to miss bow bow
.
+2
source to share
Well, there's a better way: XPath.
import lxml.html
data = """<td style="padding: 20px">blah blah </td>
<td style="padding: 21px">bow bow</td>
<td style="padding: 20px">buh buh</td>
"""
doc = lxml.html.document_fromstring(data)
for col in doc.xpath("//td[@style='padding: 20px']"):
print col.text
It's more neat as well as faster.
+3
source to share
If you prefer using a CSS selector:
import lxml.html
data = """<td style="padding: 20px">blah blah </td>
<td style="padding: 21px">bow bow</td>
<td style="padding: 20px">buh buh</td>
"""
doc = lxml.html.document_fromstring(data)
for td in doc.cssselect('td[style="padding: 20px"]'):
print td.text
+3
source to share