3 回答
TA贡献1828条经验 获得超3个赞
对于 html 元素选择Beautiful Soup是您所需要的,@QHarr答案应该有效只需检查您使用的编码。
但是,如果您想要正则表达式解决方案,只需使您的字符串变平(没有换行符)而不是搜索元素:
import re
html = """<div class="full">
<div>
<div> **<== WANT TO START GRABBING HERE **
<div>CONTENT</div>
<div>CONTENT</div>
<div>CONTENT</div>
<div>CONTENT</div>
</div> **<== STOP GRABBING HERE **
</div>
</div>"""
sep = 'xxxx****' # dummy string to replace \n and put them back
r = '<div class="full">[\s{0}]*<div>(.*)</div>[\s{0}]*</div>'.format(sep)
# search will return first matching element.
l = re.search(r, html.replace('\n',sep)).groups(0)[0]
# findall will return all element matching the pattern if you have more than one use findall
# l = re.findall(r, html.replace('\n',sep))[0]
print(l.replace(sep, '\n'))
TA贡献1863条经验 获得超2个赞
对于您的特定情况,请尝试以下正则表达式:
(<div>\s+){2}([\s\w</>]*?)(</div>\s+){2}然后从中提取所需的组。
但是,我建议改用BeautifulSoup,它更简单、更强大。
TA贡献1963条经验 获得超6个赞
您可以结合使用类和类型css 选择器以及子组合器来完成此操作
from bs4 import BeautifulSoup as bs
html = '''<div class="full">
<div>
<div>
<div>CONTENT</div>
<div>CONTENT</div>
<div>CONTENT</div>
<div>CONTENT</div>
</div>
</div>
</div>'''
soup = bs(html, 'lxml')
print(soup.select_one('.full > div > div'))
添加回答
举报
