如何仅选择具有相似ID的DIV

2024-10-03 06:25:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用漂亮的汤解析一个设计糟糕的网页。你知道吗

目前,我需要的是网页的selectthecomment部分,但每个评论都被视为一个DIV,每个评论都有一个类似“iamcoment\u00001”的ID,但仅此而已。不上课(这会有很大帮助)。你知道吗

所以我不得不搜索所有以“iamcoment”开头的div,但我不知道怎么做。我能找到的最接近的是SoupStrainer,但却不知道如何使用它。你知道吗

我怎样才能做到这一点?你知道吗


Tags: divid网页评论soupstraineru00001selectthecommentiamcoment
2条回答

我将使用BeautifulSoup's内置的find_all函数:

from bs4 import BeautifulSoup
soup = BeautifulSoup(yourhtml)
soup.find_all('div', id_=re.compile('IAMCOMMENT_'))

若要解析表单注释,首先需要找到html的注释。一种方法是:

import re
from bs4 import BeautifulSoup, Comment

soup = BeautifulSoup(myhtml)
comments = soup.find_all(text=lambda text: isinstance(text, Comment))

要在注释中找到div

for comment in comments:
    cmnt_soup = BeautifulSoup(comment)
    divs = cmnt_soup.find_all('div', attrs={"id": re.compile(r'IAMCOMMENT_\d+')})

    # do things with the divs

相关问题 更多 >