如何使用Beautiful Soup根据属性值的部分内容查找标签?
Hey there! Great question—finding tags based on partial attribute values is a common task with BeautifulSoup, and there are two clean ways to do it for your specific case (tr tags where id starts with "news"):
Method 1: Use a Lambda Function with find_all
You can pass a lambda function to the attrs dictionary to perform custom checks on the attribute value. This gives you flexibility for more complex matches if needed later. Here's how it works for your scenario:
trs = soup.find_all("tr", attrs={"id": lambda x: x and x.startswith("news")})
The lambda checks two things: first, that the id attribute exists (so x isn't None), then that its value starts with "news". This ensures you only get tr tags with valid id values that match your pattern.
Method 2: Use CSS Selectors (More Concise)
BeautifulSoup supports CSS selectors, which have built-in syntax for partial attribute matches. The ^= operator means "starts with", so you can write:
trs = soup.select("tr[id^='news']")
This is shorter and reads like standard CSS—perfect for straightforward partial matches. The select method returns a list of matching tags, just like find_all.
Bonus: Other Partial Matches
If you ever need to match other substrings, CSS selectors have you covered:
*=for any substring (e.g.,tr[id*='_4343_']to find ids containing "4343")$=for ending with a substring (e.g.,tr[id$='xxx']to find ids ending with "xxx")
Both methods will get you exactly the tr tags you're looking for. I'd recommend the CSS selector approach for this case since it's more readable and concise!
内容的提问来源于stack exchange,提问作者Windstorm1981

