selectolax
selectolax copied to clipboard
Allow regular expressions in `text_contains` / `any_text_contains`
I would like to find all script
tags within a page with contain certain keywords.
Here's how it's done via bs4
:
script_tags = soup.find_all("script", string=re.compile(r"window\.(keyword|another_keyword)"))
I'm not too sure how to go about it with selectolax
.
I could use the matches provided by .select(css).text_contains(pattern)
like so:
first_keyword_scripts = tree.select("script").text_contains("window.keyword").matches
However, if I were to do the same for the second keyword, it is difficult to create the original context created with bs4
in which:
-
script_tags
preserved the order of the script tags. In this case, I have to figure out which nodes come first, and need to merge them somehow - some scripts might contain both keywords and as such can result in duplication
Another use case for regular expressions is the ability to ignore keywords.
It would be nice to have a text_does_not_contain
function too.
I think these issues can be solved with regular expressions but I'm probably wrong.
I'd appreciate any feedback on how these examples can be run via selectolax
.
For now I have a workaround that uses the .text()
operation, which isn't really great for large script texts,
Thanks for your time and for maintaining this project!