You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:45:47