python使用lxml和xpath解析html表上的特定数据
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python使用lxml和xpath解析html表上的特定数据,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2738字,纯文字阅读大概需要4分钟。
内容图文
首先,我是python和Stack Overflow的新手,所以请客气.
这是我要从中提取数据的html页面的源代码.
网页:http://gbgfotboll.se/information/?scr=table&ftid=51168
表格在页面底部
<html>
table class="clCommonGrid" cellspacing="0">
<thead>
<tr>
<td colspan="3">Kommande matcher</td>
</tr>
<tr>
<th style="width:1%;">Tid</th>
<th style="width:69%;">Match</th>
<th style="width:30%;">Arena</th>
</tr>
</thead>
<tbody class="clGrid">
<tr class="clTrOdd">
<td nowrap="nowrap" class="no-line-through">
<span class="matchTid"><span>2014-09-26<!-- br ok --> 19:30</span></span>
</td>
<td><a href="?scr=result&fmid=2669197">Guldhedens IK - IF Warta</a></td>
<td><a href="?scr=venue&faid=847">Guldheden S?dra 1 Konstgr?s</a> </td>
</tr>
<tr class="clTrEven">
<td nowrap="nowrap" class="no-line-through">
<span class="matchTid"><span>2014-09-26<!-- br ok --> 13:00</span></span>
</td>
<td><a href="?scr=result&fmid=2669176">Romelanda UF - IK Virgo</a></td>
<td><a href="?scr=venue&faid=941">Romevi 1 Gr?s</a> </td>
</tr>
<tr class="clTrOdd">
<td nowrap="nowrap" class="no-line-through">
<span class="matchTid"><span>2014-09-27<!-- br ok --> 13:00</span></span>
</td>
<td><a href="?scr=result&fmid=2669167">Kode IF - IK Kongah?lla</a></td>
<td><a href="?scr=venue&faid=912">Kode IP 1 Gr?s</a> </td>
</tr>
<tr class="clTrEven">
<td nowrap="nowrap" class="no-line-through">
<span class="matchTid"><span>2014-09-27<!-- br ok --> 14:00</span></span>
</td>
<td><a href="?scr=result&fmid=2669147">Floda BoIF - Partille IF FK </a></td>
<td><a href="?scr=venue&faid=218">Flodala IP 1</a> </td>
</tr>
</tbody>
</table>
</html>
我需要提取时间:19:30和团队名称:Guldhedens IK-IF Warta表示第一行中的第一个和第二个表格单元格(不是第三个),以及13:00 / Romelanda UF-IK Virgo.第二个表格行等.从所有表格行开始.
如您所见,每个表行在时间之前都有一个日期,因此棘手的部分就来了.我只想从日期等于我运行此代码的日期的那些表行中获取上面提到的时间和团队名称.
到目前为止,我唯一要做的事情并不多,只能使用以下代码获取时间和团队名称:
import lxml.html
html = lxml.html.parse("http://gbgfotboll.se/information/?scr=table&ftid=51168")
test=html.xpath("//*[@id='content-primary']/table[3]/tbody/tr[1]/td[1]/span/span//text()")
print test
这给了我结果[‘2014-09-26′,’19:30’]之后,我迷失了如何遍历不同的表行,想要特定的表单元格,其中日期与我运行代码的日期匹配.
希望您能回答得更多.
解决方法:
如果我了解您,请尝试以下操作:
import lxml.html
url = "http://gbgfotboll.se/information/?scr=table&ftid=51168"
html = lxml.html.parse(url)
for i in range(12):
xpath1 = ".//*[@id='content-primary']/table[3]/tbody/tr[%d]/td[1]/span/span//text()" %(i+1)
xpath2 = ".//*[@id='content-primary']/table[3]/tbody/tr[%d]/td[2]/a/text()" %(i+1)
print html.xpath(xpath1)[1], html.xpath(xpath2)[0]
我知道这很脆弱,并且有更好的解决方案,但是它可以工作.
内容总结
以上是互联网集市为您收集整理的python使用lxml和xpath解析html表上的特定数据全部内容,希望文章能够帮你解决python使用lxml和xpath解析html表上的特定数据所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。