当只有文本是公共标识符时,是否可以上下移动DOM中的当前位置?
docker-compose.yml
如何在搜索<div>changing text</div>
<div>fixed text</div>
并升级到父级div时获取文字changing text
?
我尝试了什么:
fixed text
答案 0 :(得分:2)
这个程序可能会做你想要的:
from bs4 import BeautifulSoup
import re
html = '<body><div>changing text</div><div>fixed text</div><body>'
soup = BeautifulSoup(html)
x = soup.body.findAll(text=re.compile('fixed text'))[0].parent.previous_sibling
assert x.text == 'changing text'
答案 1 :(得分:1)
您遇到的错误是由ResultSet中的parent
调用,结果列表。如果您需要多个结果,请尝试:
x = soup.body.find_all(text=re.compile('fixed text'))
for i in x:
previous_div = i.previous_sibling
如果您不想找到多个结果,只需将find_all更改为:
x = soup.body.find(text=re.compile('fixed text')).previous_sibling
请注意,我将parent替换为previous_sibling,因为div处于同一级别