如何在BeautifulSoup/CSS选择器中处理正则表达式?
我想找一个方法,使用正则表达式在 BeautifulSoup
中查找可能包含文本 HO #
的元素,这个文本可能会有空格,而且不区分大小写。
check_ho_number3 = soup.select_one('td:-soup-contains("HO #")+ td')
print(check_ho_number3)
我该如何把我现有的正则表达式整合到 soup.select_one()
里呢?
check_regex = re.compile("HO\s?#",re.IGNORECASE)
1 个回答
1
CSS选择器
只支持CSS语法,但你可以通过string
属性来根据标签内容进行搜索:
soup.find(string=re.compile(r"HO\s?#",re.IGNORECASE))
soup.find_all(string=re.compile(r"HO\s?#",re.IGNORECASE))
要使用findNextSibling('td')
,你需要先回到你找到的对象的parent
(父级)位置。
示例
from bs4 import BeautifulSoup
import re
soup = BeautifulSoup('<table><tr><td>HO #</td><td>I am the next sibling</td></tr><tr><td>HO #</td></tr><tr><td>ho#</td><td>I am the next sibling</td></tr></table>')
for e in soup.find_all(string=re.compile(r"HO\s?#",re.IGNORECASE)):
print(e)
print(e.parent.findNextSibling('td'))
HO #
<td>I am the next sibling</td>
HO #
None
ho#
<td>I am the next sibling</td>