0

我有一个页面如下:

<div class="coupon_table" style="margin:10px 0px;">
    <div class="grid" style="height: 330px; overflow-y: auto; overflow-x: hidden;">
        <table class="grid_table" widtd="100%">
            <tbody>
                <tr>
                    <td style="widtd:20px">eee</td>
                    <td style="widtd:80px">fff</td>
                    <td style="widtd:90px">www</td>
                    <td style="widtd:90px">rrr</td>
                    <td style="widtd:80px">sss</td>
                    <td style="widtd:80px">vvvv</td>
                </tr>
                <tr class ="tt">
                    <td style="widtd:20px">eee</td>
                    <td style="widtd:80px">fff</td>
                    <td style="widtd:90px">www</td>
                    <td style="widtd:90px">rrr</td>
                    <td style="widtd:80px">sss</td>
                    <td style="widtd:80px">vvvv</td>
                </tr>
                <tr class ="tt">
                    <td style="widtd:20px">eee</td>
                    <td style="widtd:80px">fff</td>
                    <td style="widtd:90px">www</td>
                    <td style="widtd:90px">rrr</td>
                    <td style="widtd:80px">sss</td>
                    <td style="widtd:80px">vvvv</td>
                </tr>
                ....
                ....
                ....
            </tbody>
        </table>
    </div>
</div>

我想得到所有有 class 的 tr tt
所以我写了类似的东西:

p = html.document_fromstring(r.text)
for row in p.xpath('/div/div/table/tr[@class="tt"]')
     proxy.ip =  row.xpath('/td[1]')[0].text_content() 
     proxy.port = row.xpath('/td[2]')[0].text_content() 
     .....

但是row.xpath('/td[1]')没有开始搜索/div/div/table/tr[@class="tt"],它什么也没找到。
简单地解释一下,len(row.xpath('//td')) == len(p.xpath('//td'))是真的。
如果我使用 jquery , row = $('.tt').firts(), 并且row.find('td') find 将在每个具有类的 tr 处开始搜索元素tt

如何使用 lxml 实现我的目的?

4

1 回答 1

1

使用td[1]代替/td[1]

for row in p.xpath('.//div/div/table//tr[@class="tt"]'):
    proxy.ip =  row.xpath('td[1]')[0].text_content()
    proxy.port = row.xpath('td[2]')[0].text_content()

或者

for row in p.xpath('.//div/div/table//tr[@class="tt"]'):
    proxy.ip =  row.find('td[1]').text_content()
    proxy.port = row.find('td[2]').text_content()

我还在.//第一个 xpath 之前添加了匹配任何div. 替换table/trtable//tr因为trtbody标签内。

或者,您可以使用cssselect

for row in p.cssselect('div>div>table tr.tt'):
    proxy.ip =  row.cssselect('td:nth-child(1)')[0].text_content() 
    proxy.port = row.cssselect('td:nth-child(2)')[0].text_content() 
于 2013-10-11T02:45:45.873 回答