我正在使用 Python \ Selenium \ Chrome 驅動程式來執行網頁抓取。我想將一個 INT 變數 (id) 傳遞給一個 URL - 我該怎么做?我已經嘗試了以下所有方法,但這一行出現了 Python 錯誤:
id = 2000
# Part 1: Customer:
#urlg = 'https://mythirteen.co.uk/customerRest/show/?id=2000' working but need to pass variable
#urlg = 'https://mywebsite.com/customerRest/show/?id=' %(id)
#urlg = 'https://mywebsite.com/customerRest/show/?id={id}'
# urlg = 'https://mywebsite.com/customerRest/show/?id='.format(id)
# urlg = 'https://mywebsite.com/customerRest/show/?id=' id
# urlg = "https://mywebsite.com/customerRest/show/?id=".format(id)
# urlg = 'https://mywebsite.com/customerRest/show/?id=' % id
driver.get(urlg)
我收到錯誤,例如:
TypeError: not all arguments converted during string formatting
我知道它不是一個字串 - id 是 INT。
最終,我每次都需要回圈并增加 id 1 ,但現在我只想能夠傳遞實際變數。
uj5u.com熱心網友回復:
如果要連接字串和整數,對于大多數方法,您必須將整數轉換為帶有str(id).
否則我真的很喜歡使用 f-strings:
urlg = f'https://mywebsite.com/customerRest/show/?id={id}'
編輯
正如@chitown88 提到的,id用作變數不是一個好主意,因為它是在內部保留的。最好使用類似customer_id.
uj5u.com熱心網友回復:
您嘗試的方法的問題是您基本上沒有告訴它將字串放在哪里,或者嘗試連接字串和 int
所以這'https://mywebsite.com/customerRest/show/?id=' %(id)需要'https://mywebsite.com/customerRest/show/?id=%s' %(id)
所以所有這些都會起作用:
另外,我不會id用作變數,因為它是 python 中的保留函式。使其更具描述性也可能更有意義:
customerId = 2000
urlg = 'https://mythirteen.co.uk/customerRest/show/?id=2000' working but need to pass variable
urlg = 'https://mywebsite.com/customerRest/show/?id=%s' %(customerId)
urlg = 'https://mywebsite.com/customerRest/show/?id=%s' %customerId
urlg = f'https://mywebsite.com/customerRest/show/?id={customerId}'
urlg = 'https://mywebsite.com/customerRest/show/?id={}'.format(customerId)
urlg = 'https://mywebsite.com/customerRest/show/?id=' str(customerId)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/461092.html
上一篇:獲取主頁中子鏈接的鏈接和標題
下一篇:Seleniumchromedriver錯誤:AudioContext不允許啟動。它必須在頁面上的用戶手勢后恢復(或創建)
