XPATH - 有很多孩子的HTML

时间:2016-05-02 07:40:26

标签: python html python-2.7 xpath web-scraping

考虑页面变量中的html。

如何访问 td

我想像xpath("/table/tr/td/text())"

那样访问它们

我不想指出其他 tr s

不幸的是,这个表达式xpath('.//table/tr/tr/tr/td/text()')也无效。

Python代码:

import __future__
from lxml import html
import requests
from bs4 import BeautifulSoup

page = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>cv</title>
</head>
<body>

    <table>
        <tr>
            <tr>
                <tr>
                    <td>table1 td1</td>
                    <td>table1 td2</td>
                </tr>
            </tr>
        </tr>
    </table>

    <table>
        <tr>
            <tr>
                <tr>
                    <td>table2 td1</td>
                    <td>table2 td2</td>
                </tr>
            </tr>
        </tr>
    </table>

    <table>
        <tr>
            <tr>
                <tr>
                    <td>table3 td1</td>
                    <td>table3 td2</td>
                </tr>
            </tr>
        </tr>
    </table>
</body>
</html>
"""

soup = str(BeautifulSoup(page, 'html.parser'))
tree = html.fromstring(soup)

things = tree.xpath('.//table/tr/tr/tr/td/text()')

print(things)

for thing in things:
        print(thing)

print('That's all')

我想从根本开始!

3 个答案:

答案 0 :(得分:1)

使用xpath //td/text()

things = tree.xpath('//td/text()')

//td代表&#34;在任何深度找到任何td元素。

适合我。

打印按td分组的table元素:

doc = html.fromstring(page)
for table_elm in doc.xpath("//table"):
    print "another table"
    things = table_elm.xpath('.//td/text()')
    print(things)

注意,在这种情况下,xpath中的.显着。

答案 1 :(得分:1)

您无需将BeautifulSoup转换为str

soup = str(BeautifulSoup(page, 'html.parser'))

您可以使用以下内容:

>>> soup = BeautifulSoup(page, 'html.parser')
>>> for td in soup.find_all('td'):
...     print(td)
... 
<td>table1 td1</td>
<td>table1 td2</td>
<td>table2 td1</td>
<td>table2 td2</td>
<td>table3 td1</td>
<td>table3 td2</td>

或者,如果您想要元素内的文本,也可以使用print(td.text)

答案 2 :(得分:1)

tr内的

tr无效HTML。

这似乎是由html.fromstring()解析器“修复”的。

您可以使用此xpath进行测试:

things = tree.xpath('//table/tr/*')

输出:

for thing in things:
   print(thing.tag)

生成:

td
td
td
td
td