【问题标题】:How to find an html element using Beautiful Soup and regex strings如何使用 Beautiful Soup 和正则表达式字符串查找 html 元素
【发布时间】:2017-02-01 22:16:40
【问题描述】:

我正在尝试使用 python 3、漂亮的汤和正则表达式字符串在 html 文档中找到以下 <li> 元素。

<li style="text-indent:0pt; margin-top:0pt; margin-bottom:0pt;" value="394">KEANE J.
The plaintiff is a Sri Lankan national of Tamil ethnicity.  While he was a
passenger on a vessel travelling from India to
Australia, that vessel ("the
Indian vessel") was intercepted by an Australian border protection vessel ("the
Commonwealth ship")
in Australia's contiguous
zone<span class="sup"><b><a name="fnB313" href="http://www.austlii.edu.au/au/cases/cth/HCA/2015/1.html#fn313">[313]</a></b></span>. 
</li>

我尝试使用以下find_all 函数,它返回一个空列表。

html.find_all('li', string='KEANE J.')

我还尝试了带有正则表达式的find 函数,它返回一个无对象:

html.find('li', string=re.compile(r'^KEANE\sJ\.\s'))

如何在 html 文档中找到这个元素?

【问题讨论】:

  • 它适用于我,在 BeatifulSoup 4.4.1 你使用的是哪个版本的 beautifulSoup?
  • 我正在使用BeautifulSoup 4.5.1
  • 抱歉,我之前没有包含完整的元素,但我认为这与存在的&lt;span&gt; 元素有关?
  • KEANE J 可以出现在页面上任何其他文本的开头吗?
  • "基恩 J."不应出现在除此之外的任何其他段落的开头。 “基恩 J”可能会。

标签: python html regex beautifulsoup


【解决方案1】:

它与存在的元素有关吗?

当然,在这种情况下,除了文本节点之外,li 元素还有其他子节点。这记录在.string paragraph:

如果一个标签包含不止一个东西,那么.string应该指的是什么就不清楚了,所以.string被定义为None

你可以做的是定位文本节点本身,然后得到它的父节点:

li = html.find(string=re.compile(r'^KEANE\sJ\.\s')).parent
print(li)

【讨论】:

    猜你喜欢
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 2016-07-18
    相关资源
    最近更新 更多