【问题标题】:Beautiful Soup Using Regex to Find Tags?美丽的汤使用正则表达式查找标签?
【发布时间】:2014-09-05 01:44:37
【问题描述】:

我真的希望能够让 Beautiful Soup 匹配任何标签列表,就像这样。我知道 attr 接受正则表达式,但是在漂亮的汤中有什么东西可以让你这样做吗?

soup.findAll("(a|div)")

输出:

<a> ASDFS
<div> asdfasdf
<a> asdfsdf

我的目标是创建一个可以从网站抓取表格的抓取工具。有时标签的命名不一致,我希望能够输入标签列表来命名表的“数据”部分。

【问题讨论】:

  • 可以使用标签列表:soup.find_all(['a', 'div'])

标签: python regex web-scraping


【解决方案1】:

请注意,您也可以使用正则表达式在标签的属性中搜索。例如:

import re
from bs4 import BeautifulSoup

soup.find_all('a', {'href': re.compile(r'crummy\.com/')})

此示例查找链接到包含子字符串 'crummy.com' 的网站的所有 &lt;a&gt; 标记。

【讨论】:

    【解决方案2】:

    find_all() 是 Beautiful Soup 搜索 API 中最受欢迎的方法。

    您可以传递各种过滤器。另外,传递一个list 来查找多个标签:

    >>> soup.find_all(['a', 'div']) 
    

    示例

    >>> from bs4 import BeautifulSoup
    >>> soup = BeautifulSoup('<html><body><div>asdfasdf</div><p><a>foo</a></p></body></html>')
    >>> soup.find_all(['a', 'div'])
    [<div>asdfasdf</div>, <a>foo</a>]
    

    或者您可以使用regular expression 来查找包含adiv 的标签:

    >>> import re
    >>> soup.find_all(re.compile("(a|div)"))
    

    【讨论】:

      【解决方案3】:

      是的,请参阅文档...

      http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html

      import re
      
      soup.findAll(re.compile("^a$|(div)"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-21
        • 2012-05-05
        • 2017-12-14
        • 2013-06-29
        • 1970-01-01
        • 2013-04-09
        • 2017-12-05
        相关资源
        最近更新 更多