【问题标题】:Cannot locate elements by XPath on Python无法在 Python 上通过 XPath 定位元素
【发布时间】:2020-09-15 17:05:46
【问题描述】:

我试图使用 XPath 从 Bloomberg 获取公司的网站。我被卡住了,因为它总是返回一个空列表。我做了几次测试,发现我在这个网页上找不到任何元素。这是我正在使用的代码。

import re 
import requests
from lxml import html

url = "https://www.bloomberg.com/profile/company/FWLT:US"
requests=requests.get(url)
tree = html.fromstring(requests.content)
website = tree.xpath('//*[@id="root"]/div/section/div[2]/section/div/section[7]/div/text()')
print(website)

我也尝试过 selenium,但最终遇到了同样的问题。有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: python selenium xpath python-requests webdriverwait


    【解决方案1】:

    这将为您带来网站价值 -

    website = tree.xpath('//h2[contains(text(), \'WEBSITE\')]/following-sibling::div')
    

    请注意,我已经从 'WEBSITE' 中转义了单引号

    【讨论】:

    • 嗨,Alin,我试过你的,但还是不行。事实上,无论我使用什么 XPath,它都会返回空列表...
    • 那是因为网站阻止了异常访问 - 尝试打印“树” - 你会发现“我们从您的计算机网络检测到异常活动\n

      要继续,请单击下面的框让我们知道您不是机器人

    【解决方案2】:

    使用Selenium打印文本www.amecfw.com可以使用以下Locator Strategies之一:

    • 使用 xpath、following 和 get_attribute():

      print(driver.find_element_by_xpath("//h2[text()='WEBSITE']//following::div").get_attribute("innerHTML"))
      
    • 使用xpath、following-sibling和text属性:

      print(driver.find_element_by_xpath("//h2[text()='WEBSITE']//following-sibling::div").text)
      

    理想情况下,要打印文本www.amecfw.com,您必须为visibility_of_element_located() 诱导WebDriverWait,您可以使用以下Locator Strategies 之一:

    • 使用 xpath、following 和 get_attribute():

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//h2[text()='WEBSITE']//following::div"))).get_attribute("innerHTML"))
      
    • 使用xpath、following-sibling和text属性:

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//h2[text()='WEBSITE']//following-sibling::div"))).text)
      
    • 注意:您必须添加以下导入:

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

    您可以在How to retrieve the text of a WebElement using Selenium - Python找到相关讨论


    结尾

    链接到有用的文档:

    【讨论】:

      猜你喜欢
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-11
      • 1970-01-01
      相关资源
      最近更新 更多