我想摘一下香港立法的內容。但是,我無法訪問不可見的內容,除非我向下滾動頁面。網上刮刮香港電子立法
網站我訪問:https://www.elegislation.gov.hk/hk/cap211
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import ElementNotVisibleException
from selenium.webdriver.common.action_chains import ActionChains
def init_driver(profile):
driver = webdriver.Firefox(profile)
driver.wait = WebDriverWait(driver, 5)
return driver
def convert2text2(webElement):
if webElement != []:
webElements = []
for element in webElement:
e = element.text.encode('utf8')
webElements.append(e)
else:
webElements = ['NA']
return webElements
profile = webdriver.FirefoxProfile()
driver = init_driver(profile)
url = 'https://www.elegislation.gov.hk/hk/cap211'
driver.get(url)
driver.wait = WebDriverWait(driver, 5)
content = driver.find_elements_by_xpath("//div[@class='hklm_content' or @class='hklm_leadIn' or @class='hklm_continued']")
content = convert2text2(content)
瞭解,從How can I scroll a web page using selenium webdriver in python?採取下面的代碼被用於滾動瀏覽器:
SCROLL_PAUSE_TIME = 0.5
# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
# Scroll down to bottom
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# Wait to load page
time.sleep(SCROLL_PAUSE_TIME)
# Calculate new scroll height and compare with last scroll height
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
但我不能想出如何指定內容窗口的滾動條並滾動到底部。
我懷疑你的代碼將錯誤依然,但(這取決於oython版)。 py3 .text已經是utf-8編碼,因爲字符串默認是unicode。 – jlaur
您的第一個解決方案對我無效。但感謝您提出解決方案2.在對您建議的解決方案進行了一些修改後,我可以訪問該內容。 –
對不起,錯過了「;」在JavaScript的結尾處。我沒有運行代碼。它現在可以工作 - 但不適用於特定的網站,因爲您之後的內容位於框架內。因此,如果您需要幫助進入框架並在其中滾動,請檢查SO以查找相關問題 - 如果不存在,請發表新問題。 – jlaur