python使用lxml和xpath解析html表上的特定数据

标签 python xpath web-scraping html-table lxml

首先,我是 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&amp;fmid=2669197">Guldhedens IK - IF Warta</a></td>
                <td><a href="?scr=venue&amp;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&amp;fmid=2669176">Romelanda UF - IK Virgo</a></td>
                <td><a href="?scr=venue&amp;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&amp;fmid=2669167">Kode IF - IK Kongahälla</a></td>
            <td><a href="?scr=venue&amp;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&amp;fmid=2669147">Floda BoIF - Partille IF FK </a></td>
            <td><a href="?scr=venue&amp;faid=218">Flodala IP 1</a> </td>
        </tr>


                </tbody>
        </table>
    </html>

我需要提取时间:19:30 和团队名称:Guldhedens IK - IF Warta 表示第一个表格行中的第一个和第二个表格单元格(不是第三个)和 13:00/Romelanda UF - IK来自第二个表格行的处女座等等。来自所有表格行。

如您所见,每个表格行都有一个正好在时间之前的日期,所以这里是棘手的部分。我只想从日期等于我运行此代码的日期的那些表行中获取上面提到的时间和团队名称。

到目前为止我唯一能做的事情并不多,我只能使用这段代码获取时间和团队名称:

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]

我知道这很脆弱并且有更好的解决方案,但它确实有效。 ;)

编辑:
使用 BeautifulSoup 的更好方法:

from bs4 import BeautifulSoup
import requests

respond = requests.get("http://gbgfotboll.se/information/?scr=table&ftid=51168")
soup = BeautifulSoup(respond.text)
l = soup.find_all('table')
t = l[2].find_all('tr') #change this to [0] to parse first table
for i in t:
    try:
        print i.find('span').get_text()[-5:], i.find('a').get_text()
    except AttributeError:
        pass

编辑2: 页面没有响应,但应该可以:

from bs4 import BeautifulSoup
import requests

respond = requests.get("http://gbgfotboll.se/information/?scr=table&ftid=51168")
soup = BeautifulSoup(respond.text)
l = soup.find_all('table')
t = l[2].find_all('tr')
time = ""
for i in t:
    try:
        dateTime = i.find('span').get_text()
        teamName = i.find('a').get_text()
        if time == dateTime[:-5]:
            print dateTime[-5,], teamName
        else:
            print dateTime, teamName
            time = dateTime[:-5]
    except AttributeError:
        pass

lxml:

import lxml.html
url = "http://gbgfotboll.se/information/?scr=table&ftid=51168"
html = lxml.html.parse(url)
dateTemp = ""
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)
    time = html.xpath(xpath1)[1]
    date = html.xpath(xpath1)[0]
    teamName = html.xpath(xpath2)[0]
    if date == dateTemp:
        print time, teamName
    else:
        print date, time, teamName

关于python使用lxml和xpath解析html表上的特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25959839/

相关文章:

python - 使用 Scrapy 从动态 JSON 响应中提取内容

python - 将列表转换为 ID 列表

python - 如何通过 Selenium Webdriver 查找具有动态 id 的元素

Java + Selenium : Unable to Locate Element by Attribute

html - 从文件名更改的网站下载 Excel 文件

python - 使用 matplotlib 从 CSV 文件中绘制数据

python - 如何在具有不同日期格式的列上将字符串转换为日期

python - 我可以使用 python、selenium 和 lxml 解析 xpath 吗?

javascript - 尝试使用 jQuery 获取表中 img src 和 'star rating' 列的选择器

python - 我需要帮助网络抓取