使用xpath在页面上查找元素时遇到麻烦

时间:2019-12-13 14:49:30

标签: selenium xpath web-scraping

我正尝试如下所示访问数据。

HTML code

我正在使用此命令捕获信息,但无济于事。有人对我要去哪里出错有任何提示吗?

代码试用:

posts = firefox.find_elements_by_xpath(//*[@id="flotGagueValue0"])
print(posts)
for post in posts:
    print(post)

2 个答案:

答案 0 :(得分:0)

您正在寻找“ .text”。

#include <SFML/Network.hpp>
#include <iostream>

int main()
{
    // prepare the request
    sf::Http::Request request("/", sf::Http::Request::Get);

    // send the request
    sf::Http http("http://localhost:3000/");
    sf::Http::Response response = http.sendRequest(request);

    // check the status
    std::cout << response.getStatus();

    return 0;
}

出于可读性考虑,我会这样写:

posts = firefox.find_elements_by_xpath(//*[@id="flotGagueValue0"]) print(posts) for post in posts: print(post.text)

答案 1 :(得分:0)

所需元素是Angular元素,因此要提取文本 98.72 ,您必须为visibility_of_element_located()引入 WebDriverWait ,然后可以使用以下任一解决方案:

  • 使用CSS_SELECTOR text 属性:

    print(WebDriverWait(firefox, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.panel-content div.singlestat-panel > div span#flotGagueValue0"))).text)
    
  • 使用XPATHget_attribute()

    print(WebDriverWait(firefox, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='panel-content']//div[@class='singlestat-panel']/div//span[@id='flotGagueValue0']"))).get_attribute("innerHTML"))
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC