[英]I can't locate an element despite using correct CSS selector/XPATH and there is no iframe in html that I'm scraping. How do I get the element?
[英]can't locate element behind <span> on a website using xpath or css selector
在这个网页上,我检查了评论数量 - 42,我需要抓住它。 它位于这个 span 元素中
<span><i class="tn-icon-comment-dark">
</i>42</span>
将鼠标悬停在检查器菜单中的实际数字 42 上,表明它在实际网页上具有 #text 属性。
我试过这个:
from selenium import webdriver
driver = webdriver.Firefox()
news_url = 'https://tengrinews.kz/kazakhstan_news/strogiy-karantin-vvodyat-v-mangistauskoy-oblasti-408772/'
driver.get(news_url)
u =driver.find_element_by_xpath('/html/body/div[2]/main/section/div/div[4]/div[1]').get_attribute('#text')
print(u)
print(u.text)
print(u.text())
print(u.get_attribute('#text'))
driver.quit()
output:
None
Traceback (most recent call last):
File ".\curent_time_playing.py", line 17, in <module>
print(u.text)
AttributeError: 'NoneType' object has no attribute 'text'
对于这个问题,我有两种方法,
获取元素的text
并拆分它并根据 position 获取数字。 默认情况下,它返回type str
(需要类型转换,如果你想使用它作为整数)
from selenium import webdriver driver = webdriver.Firefox() news_url = 'https://tengrinews.kz/kazakhstan_news/strogiy-karantin-vvodyat-v-mangistauskoy-oblasti-408772/' driver.get(news_url) u=driver.find_element_by_xpath('/html/body/div[2]/main/section/div/div[4]/div[1]').text print(u.split()[0])
您可以直接获取该<span>
标签的xpath
并获取文本。 由于内容不是英文的,我无法弄清楚您到底在寻找哪个评论。
作为参考,您可以使用相对的 XPath:
(//div[@class="tn-comment-accordion-title"]//span)[1]
Output:
<span>
<i class="tn-icon-comment-dark"/>
31
</span>
使用.text
提取评论数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.