目前很多网站页面内容都是动态渲染出的,基于请求的方式无法获取到真实网页内容,因此开发了一个基于selenium的简单的指定url输出html的小程序。程序读取根目录url.txt文件,输出json消息。
代码如下:
import json
import undetected_chromedriver as uc
from selenium import webdriver
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.chrome.options import Options
def fetch_html(url):
driver = initDriver()
try:
driver.get(url)
html_content = driver.page_source # 获取页面HTML内容
finally:
driver.quit() # 确保最后关闭浏览器驱动
return html_content
def process_urls(file_path, output_file):
# 存储结果的列表
results = []
with open(file_path, 'r') as file:
for line in file:
url = line.strip() # 读取每行的URL
if url:
html_content = fetch_html(url) # 使用Selenium获取HTML内容
results.append({'url': url, 'html': html_content}) # 添加到结果列表
# 将结果写入JSON文件
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(results, f, ensure_ascii=False, indent=4)
def initDriver():
chrome_options = Options()
d = DesiredCapabilities.CHROME
d['goog:loggingPrefs'] = {'browser': 'ALL'}
chrome_options.add_argument('--blink-settings=imagesEnabled=false')
chrome_options.add_argument('--ignore-certificate-errors')
chrome_options.add_argument("--disable-popup-blocking")
driver = uc.Chrome(desired_capabilities=d, options=chrome_options)
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source": """
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
})
"""})
driver.maximize_window()
return driver
if __name__ == '__main__':
process_urls('url.txt', 'output.json')