簡體   English   中英

搜索正則表達式時忽略子節點

[英]Ignore children nodes when searching for regular expression

我想用BeautifulSoup識別大文本文檔中的分割點。 因此,我已經制定了一個正則表達式來查找出現特定字符串的Tag。 問題是,如果我正在搜索的字符串中還有格式/子節點,則它不起作用。

t1 = BeautifulSoup("<p class=\"p p8\"><strong>Question-And-Answer</strong></p>")

t2 = BeautifulSoup("<p class=\"p p8\"><strong>Question</strong>-<strong>And</strong>-<strong>Answer</strong></p>")

t1.find(text = re.compile("Question[s]*-And-Answer[s]*", re.IGNORECASE))
>>> 'Question-And-Answer'

t2.find(text = re.compile("Question[s]*-And-Answer[s]*", re.IGNORECASE))
>>> None

輸出應該是p Tag對象。

你在這里遇到的問題是你正在尋找的文本在p節點內被strong標簽拆分,因此.find使用text參數的正則表達式搜索將不起作用,它只是在BS中實現的方式。

如果您知道文本在p節點中 ,則可以在.find調用中使用lambda表達式,並對每個p標記的text屬性運行正則表達式搜索,以查找所需的元素:

print(t2.find(lambda t: t.name == "p" and re.search(r'Questions*-And-Answers*', t.text)))
# => <p class="p p8"><strong>Question</strong>-<strong>And</strong>-<strong>Answer</strong></p>

請注意, [s]與正則表達式中的s相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM