我想摘一下香港立法的内容。但是,我无法访问不可见的内容,除非我向下滚动页面。网上刮刮香港电子立法
网站我访问: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