我有一個腳本可以一次從 10 個多頁中抓取。
#hyperlink_list is the list of the pages
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(ChromeDriverManager().install(),options=options)
for i in range(0,10):
url = hyperlink_list[i]
sleep(randint(10, 24))
driver.get(url)
time.sleep(10)
soup = BeautifulSoup(driver.page_source, 'html.parser')
現在從頁面中,我正在提取這部分:

僅在某些頁面中,存在show more描述較長的鏈接。我想單擊此鏈接,并在show more鏈接可用時提取說明。
show more鏈接代碼:
<a id="rfq-info-header-description-showmorebutton">
show more
</a>
我只想在此鏈接可用時單擊它,否則它會顯示 element not found 錯誤。
uj5u.com熱心網友回復:
使用more = driver.find_element_by_id("rfq-info-header-description-showmorebutton")(假設始終可以使用此 id 找到more 鏈接)。如果沒有找到更多按鈕,這將引發例外。(詳情請看這里)
uj5u.com熱心網友回復:
你應該try-except阻止,我們應該尋找show more web element。下面我正在使用find_elements (plural)并len()獲取大小,如果>0必須存在 web 元素,然后嘗試使用顯式等待單擊它。
如果大小不是>0那么顯示更多不應該是可見的,我只是在該塊中列印一個簡單的列印陳述句。
代碼 :
try:
if len(driver.find_elements(By.XPATH, "//a[@id='rfq-info-header-description-showmorebutton']")) >0 :
print("Show more link is available so Selenium bot will click on it.")
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//a[@id='rfq-info-header-description-showmorebutton']"))).click()
print('Clicked on show more link')
else:
print("Show more link is not available")
except:
print('Something else went wrong.')
pass
進口:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/341173.html
