我怎么刮这个标签?

2024-10-02 06:34:01 发布

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

  <div id="hide-editing-34536258">1/2 and 2/1 are reciprocals.</div>

这是我要刮的标签,我要打印1/2 and 2/1 are reciprocals.

我将通过get_text()打印它,但我不知道如何刮标签

我能做到

find_all({"class":"hide-editing-3453658"}

但是有更多的标签需要清理,而且在“高编辑”之后,标签的编号也不同

我在数字中找不到任何规则

有人能帮我吗


Tags: andtextdivid编辑get标签all
2条回答

也许你可以试试正则表达式

import re

text = '<div id="hide-editing-34536258">1/2 and 2/1 are reciprocals.</div>'
parsedText=re.findall('>([^<]+)', text)

print(parsedText[0])

属性是id而不是class,并且您已经给出了在find_all方法中查找的标记。您可以使用regex查找具有特定模式的所有元素

In [61]: import re
In [62]: a = """  <div id="hide-editing-34536258">1/2 and 2/1 are reciprocals.</div>
    ...:    <div id="hide-editing-345258">1/4 and 2/1 are reciprocals.</div>
    ...:   <div id="hide-editing-346258">1/5 and 2/1 are reciprocals.</div>
    ...: """

In [63]: soup = BeautifulSoup(a, "html.parser")

In [64]: all_divs = dates = soup.findAll("div", {"id" : re.compile('hide-editing.*')})

In [65]: all_divs
Out[65]:
[<div id="hide-editing-34536258">1/2 and 2/1 are reciprocals.</div>,
 <div id="hide-editing-345258">1/4 and 2/1 are reciprocals.</div>,
 <div id="hide-editing-346258">1/5 and 2/1 are reciprocals.</div>]

In [66]: [i.text.strip() for i in all_divs]
Out[66]:
['1/2 and 2/1 are reciprocals.',
 '1/4 and 2/1 are reciprocals.',
 '1/5 and 2/1 are reciprocals.']

相关问题 更多 >

    热门问题