Python中的Web Scraping,与路径混淆

时间:2015-10-14 15:37:14

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

我有刮刮的基本知识。 这是一个基本的例子:

page = requests.get('some_website.com')
tree = html.fromstring(page.text)
desc = tree.path('//div[@class = "my class"]/text()')

我的desc将返回div中的任何内容。 但是,如果我的javascript更复杂,我该如何继续

<tr>
    <th class="my class">some text</th>
    <td>some text</td>
</tr>

我只需要位于<td></td><tr></tr>内的部分 如果<tr>位于<div>

内,我将如何处理?

1 个答案:

答案 0 :(得分:1)

您应该通过XPath教程来更好地理解。

  

我只需要位于<td></td><tr></tr>内的部分   如果<tr>位于<div>

内,我将如何处理?

在你的情况下,它将是:

//div[@class = "my class"]//tr/td/text()

如果您事先知道“某些文字”,则可以使用following-sibling

横向搜索
//div[@class = "my class"]//th[. = "some text"]/following-sibling::td/text()