How to select HTML element by id that is a number in beatiful soup

Viewed 147

I am trying to select an HTML element with an id that is a number, ie. <div id=27047243>

When I try to use the select method like this soup.select("#27047243") I get an error that says Malformed id selector

I figured I need to escape the number somehow, I tried like this soup.select(r"#\3{number}" but even though I did not get the error anymore, I could not get the element

I know I could use the find method soup.find(id="27047243") and that works, but the problem is I need to go deeper into nested elements so I want to know if there is a way how to do this using 'select' so I can use CSS selectors

2 Answers

You can try this:

soup.select_one('div#27047243')

You can use div[id="27047243"]:

from bs4 import BeautifulSoup

html_doc = """
<div id=27047243>
I want this.
</div>
"""

soup = BeautifulSoup(html_doc, "html.parser")
print(soup.select_one('div[id="27047243"]'))

Prints:

<div id="27047243">
I want this.
</div>
Related