簡體   English   中英

selenium 無法僅從“span”獲取“文本”

[英]Failed to get only the "text" from "span" by selenium

這是我的代碼:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service

service = Service("C:\Development\chromedriver.exe")
driver = webdriver.Chrome(service=service)

driver.get(
    "https://www.amazon.com/HB-UM43-%D7%A8%D7%9B%D7%96%D7%AA-Sabrent-USB-3-0/dp/B00JX1ZS5O/ref=d_ex_efse_dp_ps_d_sccl_2_13/134-8388945-8876241?pd_rd_w=PhytY&content-id=amzn1.sym.a33bdad7-13b2-4641-a8b3-d6f6ef5a7304&pf_rd_p=a33bdad7-13b2-4641-a8b3-d6f6ef5a7304&pf_rd_r=7R3T4DW86KG7CHFAJHJH&pd_rd_wg=fWhFq&pd_rd_r=5bc9d4df-38d2-4d93-aaee-c6e8e63dcbf4&pd_rd_i=B00JX1ZS5O&th=1")

price = driver.find_element(By.CLASS_NAME, "a-offscreen")
print(price.get_attribute('innerHTML'))

driver.quit()

我的結果:

<span dir="rtl">$</span>‎16.98‎

網站元素:

<span class="a-offscreen"><span dir="rtl">$</span>‎16.98‎</span>

我只想得到數字“16.98”,而不是得到整個元素。 當我試圖寫“.text”時,它返回“無”。

相反, .text使用get_attribute('textContent')元素可能隱藏在頁面上。

price = driver.find_element(By.CLASS_NAME, "a-offscreen")
print(price.get_attribute('textContent'))

這應該返回$16.98以獲得16.98使用字符串操作,如

print(price.get_attribute('textContent')[1:]) #this will remove `$`

.text不起作用時,您也可以嘗試使用.get_attribute('value')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM