<div id="tranData"> <div class="tyfrom"> <div id="home"><img src="http://www.v2ex.com/img/223325.png" width="80" height="80"></div> </div> <div class="fat4"> <table width="100%" cellspacing="0" cellpadding="0"> <tbody> <tr> <th colspan="5" class="abc" align="center"> 课程表 </th> </tr> </table> </div> <div class="content"> <table width="800" cellspacing="0" cellpadding="0" align="center"> <tbody> <tr><th colspan="5" class="pit" align="center">哑铃</th></tr> <td></td> </tbody> </table> </div> <div class="content"> <table width="800" cellspacing="0" cellpadding="0" align="center"> <tbody> <tr><th colspan="5" class="pit" align="center">跑步机</th></tr> <td> <tr align="center"> <td class="a1" width="320"> <a href="http://192.168.1.155/sport/record/id1661.html" target="_blank" title="38 分钟">38 分钟</a> </td> <td class="a7" width="30"> <img src="http://www.v2ex.com/img/sh_img/finish.png" title="" style="cursor:pointer;"> </td> <td class="a3" width="100">38Min.</td> <td class="a1" width="30">14:29</td> <td class="a3" width="320">15:07</td> </tr> </td> </tbody> </table> </div> <div class="content"> <table width="800" cellspacing="0" cellpadding="0" align="center"> <tbody> <tr><th colspan="5" class="pit" align="center">踏步机</th></tr> <td></td> </tbody> </table> </div>
考虑到方便表达 html 代码的结构,瘦身了内容,调整了代码格式缩进,方便大家理解我的问题
1、通过 xpath,定位到了
//*[@id="tranData"]
2、我想提取 tranData 节点,下面的跑步机内容,在这个代码中是 content[2],但页面会根据情况变化,有可能会是[6]/[7]/[8]这样。在'跑步机'所在的 content 节点里,唯一特征就是有跑步机三个字了(对,就是 text()),其它的 content 格式是一致的
3、etree.xpath,html.xpath 用什么方法能定位到这个 content,并把节点的代码弄出来呢?
4、如何按顺序提取跑步机 content 下面的 td 的 text()内容? (td 的 class 并不是每条记录都固定是 a*)
感谢大家热心解答!!
![]() | 1 kppwp 2019-06-30 18:07:52 +08:00 via iPhone //div[...../th/text()=‘跑步机’]获取父节点 用父节点遍历子节点,不要用硬编码 |
![]() | 2 my8100 2019-06-30 18:10:48 +08:00 <tr><th colspan="5" class="pit" align="center">跑步机</th></tr> <td> 这里第二行的 <td> 应该是多余的 ``` In [215]: from scrapy import Selector In [216]: sel = Selector(text=doc) In [217]: sel.xpath("//th[contains(text(), '跑步机')]/parent::tr/following-sibling::tr/td/text()").extract() Out[217]: ['\n ', '\n ', '\n ', '\n ', '38Min.', '14:29', '15:07'] In [218]: sel.xpath("//th[text()='跑步机']/parent::tr/following-sibling::tr/td/text()").extract() Out[218]: ['\n ', '\n ', '\n ', '\n ', '38Min.', '14:29', '15:07'] In [219]: ``` |
![]() | 3 my8100 2019-06-30 18:26:53 +08:00 参考 #1 的写法: ``` In [229]: sel.xpath("//tbody[tr/th/text()='跑步机']/tr[@align='center']/td/text()").extract() Out[229]: ['\n ', '\n ', '\n ', '\n ', '38Min.', '14:29', '15:07'] In [230]: ``` |