[英]How to scrape a website with an ul-li dropdown in Python?
基於問題Scraping a specific website with a search box and javascripts in Python ,我試圖從網站https://www.msci.com/esg-ratings/中獲取公司評級搜索框,在下拉菜單中選擇該名稱的所有選項(“RIO TINTO LIMITED”和“RIO TINTO PLC”,此處為“rio tinto”)並獲取圖片,其評級位於兩者的右上角。
但是,我在處理建議公司的 ul-li dropout 菜單時遇到了麻煩:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
options = webdriver.ChromeOptions()
options.add_argument('-headless')
options.add_argument('-no-sandbox')
options.add_argument('-disable-dev-shm-usage')
options.add_argument('window-size=1920,1080')
wd = webdriver.Chrome(options=options)
wd.get('https://www.msci.com/esg-ratings')
WebDriverWait(wd, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="_esgratingsprofile_keywords"]'))).send_keys("RIO TINTO")
WebDriverWait(wd, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="ui-id-1"]/li[1]'))).click()
#WebDriverWait(wd,10).until(EC.visibility_of_element_located((By.CSS_SELECTOR,"#_esgratingsprofile_esg-ratings-profile-header > div.esg-ratings-profile-header-ratingdata > div.ratingdata-container > div.ratingdata-outercircle.esgratings-profile-header-yellow > div")))
print(wd.find_element_by_xpath('//*[@id="_esgratingsprofile_esg-ratings-profile-header"]/div[2]/div[1]/div[2]/div'))
(代碼給出了 ElementClickInterceptedException。)
如何訪問“RIO TINTO LIMITED”和“RIO TINTO PLC”所需的數據?
我在處理推薦公司的 ul-li dropout 菜單時遇到了麻煩
這是意料之中的,因為您所定位的element
是通過dynamic
腳本呈現的。 您將不得不避免options.add_argument('-headless')
以克服這一點。
你這里也有問題
print(wd.find_element_by_xpath('//*[@id="_esgratingsprofile_esg-ratings-profile-header"]/div[2]/div[1]/div[2]/div'))
您嘗試打印元素的位置。 由於目標元素是CSS
呈現的icon
,因此您不能使用print()
到 output 。 相反,您需要將其另存為,例如.png
文件
with open('filename.png', 'wb') as file:
file.write(driver.find_element_by_xpath('//*[@id="_esgratingsprofile_esg-ratings-profile-header"]/div[2]/div[1]/div[2]/div').screenshot_as_png)
然后根據您的需要使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.