If I use:
import requests
from lxml import html
response = request.get(url='someurl')
tree = html.document_fromstring(response.text)
all_text = tree.xpath('//text()') # which give all text from page
Inside this all_text list we have all the text from page. Now I want to know if:
text_searched = all_text[all_text.index('any string which is in all_text list')]
Is it possible to get to the web element of the text been searched?
You can use
getparent()
method for this purpose, for example :Note that the behavior of
getparent()
might not be the one you expected in case current text element located after element node in the same parent element. Due to the tree model implemented bylxml
, the text is consideredtail
of the preceding element instead ofchild
of the containing element in this case, sogetparent()
will return the preceding element. See example below to get a clear idea of what I've been talking about :