简体   繁体   English

Python Selenium XPath获取文本为空

[英]Python selenium xpath geting text is empty

So I have this link and I'm trying to obtain the text from this XPath //div[@class='titlu'] but for some reason sometimes I'm getting the text how it should be and other times I'm receiving an empty string even though the site is containing that text. 所以我有了这个链接 ,我试图从该XPath //div[@class='titlu']获取文本,但是由于某些原因,有时我会得到文本的样子,而有时我会收到一个空字符串,即使该站点包含该文本也是如此。

What have I tried: 我尝试了什么:

wait = WebDriverWait(self.driver, 10)   
wait.until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, "Ap. de lux 3 ")))
e = self.driver.find_element_by_xpath(html_data.xpath)

also: 也:

wait = WebDriverWait(self.driver, 10)
wait.until(EC.presence_of_element_located((By.XPATH, xpath)))
e = self.driver.find_element_by_xpath(xpath)

and also I've used and this type of wait: 而且我也用过这种类型的等待:

self.driver.implicitly_wait(10)

How I'm getting the text at this moment: 我现在如何获得文本:

self.driver.find_element_by_xpath(xpath).text

the problem that I've faced here is that the text is refusing to appear on some occasions and in others it does, even though the actually XPath is found and it exists already. 我在这里面临的问题是,即使找到了实际的XPath并且它已经存在,该文本也拒绝在某些情况下出现,而在其他情况下却拒绝出现。 Maybe is not loaded completely, can any of you give me some advice about how can I fix this? 也许没有完全加载,你们中的任何人都可以给我一些有关如何解决此问题的建议吗?

UPDATE: 更新:

Also, I'm trying to get the location and size of that using selenium but both of them are going to be 0. Any idea how can I fix that? 另外,我正在尝试使用硒来获取位置和大小,但是它们都将为0。我知道如何解决这个问题吗?

with, height = self.driver.find_element_by_xpath(html_data.xpath).size x, y = self.driver.find_element_by_xpath(html_data.xpath).location

//div[@class='titlu']的第一个元素被隐藏,如果使用.text ,您将不会获得价值,因为它将仅提取可见文本,使用.get_attribute('textContent')或选择第二个元素。

You can execute script to access. 您可以执行脚本进行访问。 I learnt this method from an answer by @pguardiario 我从@pguardiario的答案中学到了这种方法

from selenium import webdriver

d = webdriver.Chrome()
d.get("https://www.imobiliare.ro/inchirieri-apartamente/sibiu/hipodrom-4/apartament-de-inchiriat-3-camere-X84T100B2?lista=2361394")
items = d.execute_script("return [...document.querySelectorAll('div.titlu')].map(item => item.innerText)")
print(items)
d.quit()

@QHarr answer returns required output (+1), but as alternative to that the same output can be achieved with common approach without using JavaScript executor: @QHarr答案返回所需的输出(+1),但作为替代方案,可以使用通用方法在不使用JavaScript执行器的情况下实现相同的输出:

from selenium import webdriver

d = webdriver.Chrome()
d.get("https://www.imobiliare.ro/inchirieri-apartamente/sibiu/hipodrom-4/apartament-de-inchiriat-3-camere-X84T100B2?lista=2361394")
items = [item.get_attribute('innerText') for item in d.find_elements_by_xpath("//div[@class='titlu']")]
print(items)
d.quit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM