pythonxpath遍历段落并抓取<strong>

2024-06-16 06:37:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用xpath解析一系列段落。html的格式如下:

<div id="content_third">
 <h3>Title1</h3>
 <p>
  <strong>District</strong>
  John Q Public <br>
  Susie B Private 
 <p>
 <p>
  <strong>District</strong>
  Anna C Public <br>
  Bob J Private 
 <p>
 <h3>Title1</h3>
 <p>
  <strong>District</strong>
  John Q Public <br>
  Susie B Private 
 <p>
 <p>
  <strong>District</strong>
  Anna C Public <br>
  Bob J Private 
 <p>
</div>

我正在设置一个初始循环,如下所示:

^{pr2}$

然后是一个内环:

district_races = tree.xpath('//*[@id="content_third"]/p[count(preceding-sibling::h3)={0}]'.format(num))
for index in range(len(district_races)):

在每个循环中,我只想选择strong内的“区域”。我试过这个方法,除了一个填充了所有区域的数组外,它会弹出空数组:

zone = tree.xpath('//*[@id="content_third"]/p[count(preceding-sibling::h3)={0}/strong[{1}]/text()'.format(num, index))

一定喜欢那些没有格式的州选举网页。在


Tags: brdivid格式contentprivatepublicjohn
1条回答
网友
1楼 · 发布于 2024-06-16 06:37:49

我假设每个地区都是某个实际名称的占位符,因此要获得每个地区比您要做的要简单得多,只需从每个strong中提取文本

h = """<div id="content_third">
 <h3>Title1</h3>
 <p>
  <strong>District</strong>
  John Q Public <br>
  Susie B Private
 <p>
 <p>
  <strong>District</strong>
  Anna C Public <br>
  Bob J Private
 <p>
 <h3>Title1</h3>
 <p>
  <strong>District</strong>
  John Q Public <br>
  Susie B Private
 <p>
 <p>
  <strong>District</strong>
  Anna C Public <br>
  Bob J Private
 <p>
</div>"""

from lxml import html

tree = html.fromstring(h)

print(tree.xpath('//*[@id="content_third"]/p/strong/text()'))

相关问题 更多 >