def parse_header(table):
ths = table.xpath('//tr/th')
if not ths:
ths = table.xpath('//tr[1]/td') # here is the problem, this will find tr[1]/td in all html file insted of this table
# bala bala something elese
doc = html.fromstring(html_string)
table = doc.xpath("//div[@id='divGridData']/div[2]/table")[0]
parse_header(table)
我想在我的表中找到所有tr[1]/td
,但table.xpath("//tr[1]/td")
仍在html文件中找到所有内容。我怎样才能找到这个元素而不是所有的html文件?
编辑:
content = '''
<root>
<table id="table-one">
<tr>
<td>content from table 1</td>
<tr>
<table>
<tr>
<!-- this is content I do not want to get -->
<td>content from embeded table</td>
<tr>
</table>
</table>
</root>'''
root = etree.fromstring(content)
table_one = root.xpath('table[@id="table-one"]')
all_td_elements = table_one.xpath('//td') # so this give me too much!!!
现在我不想要嵌入表格内容,我该怎么做?
答案 0 :(得分:1)
要查找作为上下文节点的子元素的元素,请将句点.
运算符添加到XPath中。所以,我认为您正在寻找的XPath是:
.//tr[1]/td
这将选择作为当前表的子元素的td
元素,而不是整个HTML文件。
举个例子:
from lxml import etree
content = '''
<root>
<table id="table-one">
<tr>
<td>content from table 1</td>
<tr>
</table>
<table id="table-two">
<tr>
<td>content from table 2</td>
<tr>
</table>
</root>'''
root = etree.fromstring(content)
table_one = root.xpath('table[@id="table-one"]')
# this will select all td elements in the entire XML document (so two elements)
all_td_elements = table_one.xpath('//td')
# this will just select the single sub-element because of the period
just_sub_td_elements = table_one.xpath('.//td')