【问题标题】:Locating tags via styles - using Python 2 and BeautifulSoup 4通过样式定位标签 - 使用 Python 2 和 BeautifulSoup 4
【发布时间】:2015-10-12 17:14:57
【问题描述】:

我正在尝试使用 BeautifulSoup 4 从 HTML 文档中的特定标签中提取文本。我的 HTML 有一堆 div 标签,如下所示:

<div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:42px; top:90px; width:195px; height:24px;">
  <span style="font-family: FIPXQM+Arial-BoldMT; font-size:12px">
    Futures Daily Market Report for Financial Gas
    <br/>
    21-Jul-2015
    <br/>
   </span>
</div>
<div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:54px; top:135px; width:46px; height:10px;">
  <span style="font-family: FIPXQM+Arial-BoldMT; font-size:10px">
    COMMODITY
    <br/>
   </span>
</div>

我正在尝试从样式为“left:54px”的任何 div 标签中的所有 span 标签中获取文本。

如果我使用,我可以获得一个 div:

soup = BeautifulSoup(open(extracted_html_file))
print soup.find_all('div',attrs={"style":"position:absolute; border: textbox 1px solid; "
                                         "writing-mode:lr-tb; left:42px; top:90px; "
                                         "width:195px; height:24px;"})

返回:

[<div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:42px; top:90px; width:195px; height:24px;"><span style="font-family: FIPXQM+Arial-BoldMT; font-size:12px">Futures Daily Market Report for Financial Gas
<br/>21-Jul-2015
<br/></span></div>]

但这只会让我得到一个与该样式完全匹配的 div。我想要所有只匹配“left:54px”样式的 div。

为此,我尝试了几种不同的方法:

soup = BeautifulSoup(open(extracted_html_file))
print soup.find_all('div',style='left:54px')
print soup.find_all('div',attrs={"style":"left:54px"})
print soup.find_all('div',attrs={"left":"54px"})

但是所有这些打印语句都返回空列表。

有什么想法吗?

【问题讨论】:

    标签: python html beautifulsoup inline-styles


    【解决方案1】:

    您可以根据此处的文档传入正则表达式而不是字符串:http://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-keyword-arguments

    所以我会试试这个:

    import re
    
    soup = BeautifulSoup(open(extracted_html_file))
    soup.find_all('div', style = re.compile('left:54px'))
    

    【讨论】:

    • 谢谢!那成功了!我应该仔细看看文档。
    猜你喜欢
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 2016-10-17
    • 2011-04-21
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多