【问题标题】:Regex: How to find attribute in html, that includes another attribute正则表达式:如何在 html 中查找包含另一个属性的属性
【发布时间】:2016-02-23 10:04:51
【问题描述】:

在此 HTML 代码中:

<frameset border="0" framespacing="0" frameborder="0" rows="85,*">
<frame border="0" marginheight="0" name="logoframe" scrolling="no" noresize target="middle" src="a.html" onload="reload()">

<frameset cols="235,*">
<frame border="0" name="left" src="b.html" scrolling="no"><frame border="0" noresize name="main" src="c.html"  scrolling="auto"></frameset><noframes>
<body topmargin="0" leftmargin="0">
<p>This page uses frames, but your browser doesn't support them.</p></body>         
</noframes>
</frameset></html>

我想找到包含name="main"src 属性 在这个例子中它应该返回c.html

【问题讨论】:

标签: python html regex beautifulsoup


【解决方案1】:

这可以使用BeautifulSoup 来完成,如下所示:

from bs4 import BeautifulSoup

html = """<frameset border="0" framespacing="0" frameborder="0" rows="85,*">
<frame border="0" marginheight="0" name="logoframe" scrolling="no" noresize target="middle" src="a.html" onload="reload()">

<frameset cols="235,*">
<frame border="0" name="left" src="b.html" scrolling="no"><frame border="0" noresize name="main" src="c.html"  scrolling="auto"></frameset><noframes>
<body topmargin="0" leftmargin="0">
<p>This page uses frames, but your browser doesn't support them.</p></body>         
</noframes>
</frameset></html>"""

soup = BeautifulSoup(html)

frame = soup.find('frame', attrs={'name': 'main'})
print frame['src']

它将显示文本:

c.html

【讨论】:

    【解决方案2】:

    使用 JQuery,您可以简单地执行以下操作,

    var srcFetched = $("input[name='main']").attr("src");
    alert(srcFetched);
    

    【讨论】:

    • 我可以用 beautifulsoup 做类似的事情吗?
    【解决方案3】:

    最好使用 HTML 或 XML 解析器HTML 或 XML 内容中提取值,正则表达式很好,但我仍然更喜欢 Parser 从 html 内容中提取数据。

    有人通过Beautifulsoup回答。

    以下是lxml解析器

    演示

    >>> from lxml import html as PARSER 
    >>> root = PARSER.fromstring(html)
    >>> root.xpath("//frame")
    [<Element frame at 0xb748e414>, <Element frame at 0xb748eb94>, <Element frame at 0xb748e5a4>]
    >>> root.xpath("//frame[@name='main']")
    [<Element frame at 0xb748e5a4>]
    >>> root.xpath("//frame[@name='main']/@src")
    ['c.html']
    >>> 
    

    在上面的代码中,

    1. 我们通过fromstring方法创建对象
    2. 使用xpath方法查找目标值和标签。
    3. 使用xpath 中的条件来获取目标数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2010-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多