我正在嘗試從以下站點匯入單個陣列中的所有代碼(安全符號):https ://indexes.nasdaqomx.com/Index/Weighting/NQUSS
我發現了兩個主要問題:
我每次都必須切換頁面,這樣我就不能在一個陣列中匯入所有值
我不確定元素是否正確寫入(元素應該是存盤所有 2000 多個安全符號的單個陣列
這是我寫的代碼
from builtins import print, input, int
from selenium import webdriver as wd
wd = wd.Chrome()
wd.implicitly_wait(10)
wd.get('https://indexes.nasdaqomx.com/Index/Weighting/NQUSS')
#this for allow the code to skip to the next page
for n in range(0,22):
#ticker is the xpath referring to the column of the security symbol
ticker = wd.find_elements_by_xpath("/html/body/div[1]/div/div/section[2]/div/div/div[1]/table/tbody/tr/td[3]")
try:
#this for should take all value in the current page and store them in the list elements
for i in range(0,100):
elements = [elem.text for elem in ticker]
finally:
#this line is used to go the next page
wd.find_element_by_xpath('/html/body/div[1]/div/div/section[2]/div/div/div[1]/div[1]/a[2]/img').click()
#at the end it should print all the values contained in the single array called elements
for i in range(0,3000):
print(elements[i].text)
最終結果應該是一個陣列,其中所有安全符號都存盤為字串,以便我可以在我的代碼中與它們互動,該陣列應該是元素串列。提前致謝
uj5u.com熱心網友回復:
為了將所有文本放在公共陣列中,您需要在回圈之外定義該陣列。
此外,您可以輕松地改進您在此處使用的定位器。
此外,您最終列印收集的資料時無需申請.text,elements[i]因為您已經收集了文本,而不是 Web 元素。
這應該會更好:
from builtins import print, input, int
from selenium import webdriver as wd
wd = wd.Chrome()
wd.implicitly_wait(10)
wd.get('https://indexes.nasdaqomx.com/Index/Weighting/NQUSS')
#this for allow the code to skip to the next page
elements = []
for n in range(0,22):
#ticker is the xpath referring to the column of the security symbol
tickers = wd.find_elements_by_xpath("//table[@id='weightingsTable']//td[3]")
try:
#this for should take all value in the current page and store them in the list elements
for el in tickers:
elements.append(el.text)
finally:
#this line is used to go the next page
wd.find_element_by_xpath("//a[@class='paginate_button next']").click()
#at the end it should print all the values contained in the single array called elements
for i in range(0,3000):
print(elements[i])
我還建議在這里使用預期條件顯式等待而不是隱式等待,并且不要對范圍使用預定義的硬編碼for i in range(0,3000)
這樣會更好
for idx, val in enumerate(elements):
print(elements[idx])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/430270.html
