Pytanie:Rozszerzanie selektorów CSS w BeautifulSoup
BeautifulSoup
zapewnia bardzo ograniczone wsparcie dla CSS selectors. Na przykład, jedyną obsługiwaną pseudoklasą jest nth-of-type
, która akceptuje tylko wartości liczbowe - argumenty takie jak even
lub odd
są niedozwolone.
Czy można rozszerzyć selektory CSS na BeautifulSoup
, czy też użyć wewnętrznie jako lxml.cssselect
jako mechanizmu selekcji CSS?
Weźmy spojrzeć na przykład problemu/przypadek użycia. Zlokalizuj tylko nawet wiersze w następujący kod HTML:
<table>
<tr>
<td>1</td>
<tr>
<td>2</td>
</tr>
<tr>
<td>3</td>
</tr>
<tr>
<td>4</td>
</tr>
</table>
W lxml.html
i lxml.cssselect
, to łatwo zrobić poprzez :nth-of-type(even)
:
from lxml.html import fromstring
from lxml.cssselect import CSSSelector
tree = fromstring(data)
sel = CSSSelector('tr:nth-of-type(even)')
print [e.text_content().strip() for e in sel(tree)]
Ale w BeautifulSoup
:
print(soup.select("tr:nth-of-type(even)"))
rzucał błąd:
NotImplementedError: Only numeric values are currently supported for the nth-of-type pseudo-class.
pamiętać, że możemy obejść go .find_all()
:
print([row.get_text(strip=True) for index, row in enumerate(soup.find_all("tr"), start=1) if index % 2 == 0])
Dzięki za silne "Nie wyobrażam sobie, że jest to poważnie używane wszędzie, nigdy!" :) – alecxe