pchryss
pchryss

Reputation: 39

How do I include a "-" in my code when it is part of a HTML class attribute?

I am brand new to Python/Web scraping

I am currently trying to web-scrape data from a website that has a class attribute of "data-row". However, whenever I attempt to use this attribute it splits data/row in half and shows a problem ("Expected parameter name Pylance). Is there any way to include this "-" in the code?

Example of code that works

exampleVariable = exampleDocument.find("tr", **id**="0")

Example of code I want to fix

exampleVariable = exampleDocument.find("tr", **data-row**="0")

Upvotes: 1

Views: 62

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195408

Use attrs= parameter of .find function:

from bs4 import BeautifulSoup

html_code = """\
<tr data-row="0">Some data</tr>"""

soup = BeautifulSoup(html_code, "html.parser")


tr = soup.find("tr", attrs={"data-row": "0"})
print(tr)

Prints:

<tr data-row="0">Some data</tr>

Or: Use CSS selector and .select_one method:

tr = soup.select_one('tr[data-row="0"]')

Upvotes: 2

Related Questions