【问题标题】:How do I scrape this tag?我如何刮掉这个标签?
【发布时间】:2020-07-21 04:42:26
【问题描述】:
  <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"}

但是有更多的标签要刮,并且在'high-editing-'之后它们有不同的数字

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

谁能帮帮我?

【问题讨论】:

    标签: python python-3.x web-crawler


    【解决方案1】:

    属性是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.']
    

    【讨论】:

    • 谢谢。我试过你的代码,但它说'名称're'未定义'我该怎么办?
    • 我的版本是3.8
    • 多亏了你,我解决了!当我被卡住时,我如何弄清楚我需要什么功能?
    • 这取决于html标签的属性。您可以使用findfindAllfind_all
    • 有什么办法可以排除某些带有特定模式的标签吗?当我使用 find_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])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-02
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 2021-01-04
      • 1970-01-01
      相关资源
      最近更新 更多