How do I pull <p> tags without attributes using Beautiful Soup?

*爱你&永不变心* 提交于 2021-02-05 07:46:18

问题


Say a web page contains the following:

<p style="display: none;"><input id="ak_js" name="ak_js" type="hidden" value="68"/></p>

<p><b>Lack of sales.. ANY sales.</b></p>

I'm trying to write code that would pull only the second tag. Basically all paragraph tags that don't contain attributes. I tried the following two pieces of code below, but they don't get me the results I want.

text = BeautifulSoup(requests.get(url).text)

for tag in text.find_all("p", attrs = False):
    .....

for tag in text.find_all(re.compile("^<p>$")):
    ....

What's the best way to solve this?


回答1:


You can give a lambda to find_all and filter with it.

soup.find_all(lambda tag: tag.name == 'p' and not tag.attrs)


来源:https://stackoverflow.com/questions/34111426/how-do-i-pull-p-tags-without-attributes-using-beautiful-soup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!