Html 使用xpath获取div文本,包括链接文本
获取Tweet div全文作为一个返回值(包括链接文本)的xpath选择器是什么Html 使用xpath获取div文本,包括链接文本,html,xpath,Html,Xpath,获取Tweet div全文作为一个返回值(包括链接文本)的xpath选择器是什么 //*[contains(@class, 'tweet-text')][2]/text() 对于没有链接的div,上面的方法也可以,但是当tweet包含链接时,它只返回第一个字符串段 对于没有链接的div,上面的方法也可以,但是当tweet包含链接时,它只返回第一个字符串段 这是因为/text()部分-基本上只匹配顶级文本子节点。要在任何级别匹配元素内的所有文本节点,可以执行以下操作: //*[contains(
//*[contains(@class, 'tweet-text')][2]/text()
对于没有链接的div,上面的方法也可以,但是当tweet包含链接时,它只返回第一个字符串段
对于没有链接的div,上面的方法也可以,但是当tweet包含链接时,它只返回第一个字符串段
这是因为/text()
部分-基本上只匹配顶级文本子节点。要在任何级别匹配元素内的所有文本节点,可以执行以下操作:
//*[contains(@class, 'tweet-text')][2]//text()
这通常是由HTML解析器在请求节点的“文本”值时自动完成的——它们递归地转到所有子节点并获取“文本”值——然后加入它们
使用Python+解析器演示上述内容:
[1]中的:从lxml.html导入fromstring
在[2]:html=“”
...:
…:此处为div文本
...:
...: """
在[3]中:root=fromstring(html)
[4]:root.xpath(“//div/text()”)#您可以共享您正在测试的url吗?请用这些信息更新您的问题。
In [1]: from lxml.html import fromstring
In [2]: html = """
...: <div>
...: div text here
...: <a href="https://google.com">link text</a>
...: </div>"""
In [3]: root = fromstring(html)
In [4]: root.xpath('//div/text()') # <- No text of the a element
Out[4]: ['\n div text here\n ', '\n']
In [5]: root.xpath('//div//text()') # <- We've got all the texts now
Out[5]: ['\n div text here\n ', 'link text', '\n']
In [6]: root.xpath("//div")[0].text_content() # <- but this would that for us
Out[6]: '\n div text here\n link text\n'