【问题标题】:How can I access inside given xpath result?如何访问给定的 xpath 结果?
【发布时间】:2020-11-17 21:05:31
【问题描述】:

我正在尝试抓取这样的网页

<html>
etc etc..
<div id='due'>
    <h2>title</h2>
    <div>
        <div class='desc'>
           sub1
        </div>
    </div>
    <div>
        <div class='desc'>
           sub2
        </div>
    </div>
    <div>
        <div class='desc'>
           subn
        </div>
    </div>
    <h2>title2</h2>
    <div>
        <div class='desc'>
           sub1
        </div>
    </div>
    <div>
        <div class='desc'>
           sub2
        </div>
    </div>
    <div>
        <div class='desc'>
           subn
        </div>
    </div>
</div>
etc etc..
</html>

我首先尝试抓取该部分:

box = tree.xpath('//*[@id="due"]/*')

然后:

for div in box:
    print(div.tag)

它正确返回每个元素的每个第一个标签,但是如果:

for div in box:
    if div.tag == 'div':
        print(div.xpath('//div[@class="desc"]').text)

从起始文档而不是从每个单独的 'div' 进行 n 次相同的搜索

我希望:

sub1
sub2
subn
sub1
sub2
subn

它返回,列表没有“.text”属性,但如果我打印每个列表:

[sub1, sub2, subn, sub1, sub2, subn]
[sub1, sub2, subn, sub1, sub2, subn]
[sub1, sub2, subn, sub1, sub2, subn]
[sub1, sub2, subn, sub1, sub2, subn]
[sub1, sub2, subn, sub1, sub2, subn]
[sub1, sub2, subn, sub1, sub2, subn]

是的,您会认为我应该运行一次代码,但我需要在每次迭代中进行一些变化并创建数据关系,那么我该如何解决这个问题?

在此感谢您

【问题讨论】:

    标签: python-3.x xpath web-scraping


    【解决方案1】:

    最后我没有用xpath解决问题,我只是搬到了bs4

    【讨论】:

      【解决方案2】:

      为了将来参考,用 xpath 解决你的问题试试这个:

      import lxml.html as lh
      scr = """[your html above]"""
      doc = lh.fromstring(scr)
      for t in doc.xpath('//div[@id="due"]//div[@class="desc"]/text()'):
          print(t.strip())
      

      输出:

      sub1
      sub2
      subn
      sub1
      sub2
      subn
      

      【讨论】:

      • 这个解决方案的问题是你在运行python循环之前过滤数据,我需要在for循环内过滤,因为如果div.tag不是一个div,我需要进行其他操作和与下一个传入数据链接到下一个不是 div 的div.tag
      • @Onyx 恐怕我听不懂你。它确实适用于问题中的 html。
      • 是的,它有效,但正如我在最后的主要问题上所说,我需要根据div.tag 值创建数据关系,而您实际上只是删除不是&lt;div&gt; 的框,在我的示例代码中,如果您在没有声明 if div.tag == 'div': 的情况下进行迭代,则会在 xpath 列表中获得所有结果,因此我想根据 div.tag 的值采取不同的操作,例如如果 div.tag == 'h2': 然后在 X dict 中创建另一个键, if div.tag == 'div': 然后将&lt;div&gt; 中的文本链接到一个列表中,并将列表与在 X dict 上创建的最后一个键链接,类似这样
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 1970-01-01
      • 2020-06-30
      • 2017-04-19
      • 1970-01-01
      相关资源
      最近更新 更多