【发布时间】:2021-04-14 14:11:54
【问题描述】:
我正在尝试使用遵循此模式的 BS4 在 python 中使用网站:
<p>
Text 1
<br/>
Text 2
<br/>
Text 3
<br/>
Text 4
</p>
我为此编写的代码跳过了“Text 1”和“Text 4”:
for br in scraper.findAll('br'):
next_s = br.nextSibling
if not (next_s and isinstance(next_s,NavigableString)):
continue
next2_s = next_s.nextSibling
if next2_s and isinstance(next2_s,Tag) and next2_s.name == 'br':
text = str(next_s).strip()
if text:
wanted_text = next_s.split('Text ')[1]
我知道它没有抓取 p 标签中的第一个和最后一个文本的原因是因为我的第二个 if 语句,因此我试图弄清楚是否有不同的方法来解析它。
一旦我能够获取每个“Text 1”字符串,我将使用正则表达式解析每个字符串以获取我实际需要的内容,因此此代码的所需输出将是 next_s = "Text 1"
【问题讨论】:
标签: python-3.x web-scraping beautifulsoup