我試圖從鏈接中抓取瑞士憲法的文本并將其轉換為markdown。然而,頁面的源代碼與我在檢查器中看到的不同。源檔案只包含各種語言的無腳本警告,元素"app-root"被隱藏。
檢查器顯示了一個從這里提供的.html檔案,通過該檔案我可以獲得所需的結果。然而,直接使用這個檔案將不允許我自動搜刮該法律的后續修訂。有什么方法可以提取顯示有 "app-root "元素的頁面源嗎?
這段代碼回傳 "無",但在URL設定為.html檔案的情況下可以作業:
from selenium import webdriver
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver import FirefoxOptions
from bs4 import BeautifulSoup
from markdownify import markdownify
url = "https://www.fedlex.admin.ch/eli/cc/1999/404/en"/span>
opts = FirefoxOptions()
opts.add_argument("-headless")
driver = webdriver.Firefox(executable_path=GeckoDriverManager().install(), options=opts)
driver.get(url)
html = driver.page_source
soup = BeautifulSoup(html, "html.parser")
div = soup.find("div"/span>, {"id"/span>: "lawcontent"})
content = markdownify(str(div))
print(content[:200] )
非常感謝任何幫助。
uj5u.com熱心網友回復:
在你的代碼中,你沒有給任何時間讓驅動程式渲染內容,導致源代碼不完整。
Waits可用于等待所需元素的可見/存在等。下面給出的代碼將等待div內容可見,然后回傳頁面源代碼。
代碼片段-
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
url = "https://www.fedlex.admin.ch/eli/cc/1999/404/en"/span>
驅動程式.get(url)
try:
delay=20 #20秒延遲。
WebDriverWait(driver, delay).until(EC.visibility_of_element_located((By.ID, 'lawcontent'))
html = driver.page_source
soup = BeautifulSoup(html, "html.parser")
div = soup.find("div"/span>, {"id"/span>: "lawcontent"})
content = markdownify(str(div))
print(content[:200] )
#raises Exception if element is not visible within delay duration[/span].
except TimeoutException:
print("Timeout!!")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/309735.html
標籤:
