[英]How to extract the price of the book from website using Selenium Python
[英]How to get the price as a number from a website using Selenium and Python
我正在創建一個機器人,它可以自動化我的工作並從特定網站復制特定值。 一切正常,但我的代碼的最后幾行 w.text 產生的結果是文本,我需要一個數字。 檢查后,我需要的每個元素的值如下所示:
<span class="good">€25,217.65</span>
如何將值作為數字而不是文本獲取? 我嘗試了 w.value 或 w.get_attribute('value) 但它不起作用。 這是我的程序(不包括庫和文件的下載)
driver = webdriver.Chrome(driver_path)
driver.get('https://seabass-admin.igp.cloud/')
# waiting for login table to load
try:
element = WebDriverWait(driver,10).until(
ec.presence_of_element_located((By.XPATH,'//*[@id="email"]'))
)
except:
driver.quit()
#entering sensitive info
driver.find_element_by_id("email").send_keys(pwx.em) # login details
driver.find_element_by_id("password").send_keys(pwx.pw) # password
details
driver.find_element_by_xpath('//*[@id="appContainer"]/div/form/button').click() # click sign in
# waiting for page to load
try:
element = WebDriverWait(driver,10).until(
ec.presence_of_element_located((By.XPATH,'//*
[@id="testing"]/section/section[4]/div/table/tbody/tr[2]/td[3]/span'))
)
except:
driver.quit()
# getting info from the page
w = driver.find_element_by_xpath('//*
[@id="testing"]/section/section[4]/div/table/tbody/tr[2]/td[3]/span')
cell = outcome['import']
cell[withdrawal_cell].value = w.text
根據您共享的 HTML:
<span class="good">€25,217.65</span>
文本€25,217.65是innerHTML 。
因此,您可以使用以下任一方法提取文本€25,217.65 :
w.get_attribute("innerHTML")
現在要獲得價值€25,217.65作為數字而不是文本,您需要:
使用re.sub()
刪除€
和,
字符:
import re string = "€25,217.65" my_string = re.sub('[€,]', '', string)
最后,要將字符串轉換為浮點數,您需要將字符串作為參數傳遞給float()
,如下所示:
my_number = float(my_string)
所以整個操作在一行中:
import re
string = "€25,217.65"
print(float(re.sub('[€,]', '', string)))
實際上,您的代碼行可以是以下任何一種:
使用文本屬性:
cell[withdrawal_cell].value = float(re.sub('[€,]', '', w.text))
使用get_attribute("innerHTML")
:
cell[withdrawal_cell].value = float(re.sub('[€,]', '', w.get_attribute("innerHTML")))
您可以為此使用一些 Python 的內置函數:
具體來說:
str_w = w.text # this is the '€25,217.65' string
digits=str_w.strip('€').replace(',','') # use the functions above to get number-like string
cell[withdrawal_cell].value = float(digits) # convert to float number
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.