最近工作需要使用python爬取一些網頁數據,爬取網頁是非靜態頁面
1、只能爬取靜態頁面
2、seleium需要下注對應版本的瀏覽器驅動,若是瀏覽器升級,驅動還得重新下載對應版本的驅動程序,pass
3、最終選擇的庫,可以開啟一個無界面瀏覽器,可以模擬瀏覽器打開一個頁面,并輸入url最終加載指定頁面
1、安裝庫
# 模擬無界面瀏覽器
pip install pyppeteer
# 頁面解析
pip install beautifulsoup4
2、非靜態頁面爬取demo
# _*_ coding: utf-8 _*_
# @Time: 2023/12/26
# @TODO: 爬取非靜態頁面demo
# @Author: wkq
import asyncio
from pyppeteer import launch

async def fetch_page_content(url):
"""
todo 異步請求發送
:param url: 非靜態頁面url
:return: content頁面內容
"""
# 啟動無界面瀏覽器
browser = await launch(headless=True)
# 創建一個新的頁面
page = await browser.newPage()
# 訪問目標URL并等待頁面加載完成
await page.goto(url, {'waitUntil': 'networkidle2'})
# 獲取頁面的HTML內容
content = await page.content()
await browser.close() # 關閉瀏覽器
return content
async def main():
"""

todo 異步執行請求加載頁面,解析頁面
:return:
"""
# 非靜態頁面url
url = "https://www.sporttery.cn/jczx/jclq/ssjx/20231225/10039058.html"
html_content = await fetch_page_content(url)
# 使用BeautifulSoup解析HTML
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_content, 'html.parser')
# 打印整個網頁的HTML內容
print(soup.prettify())
if __name__ == "__main__":
# 使用事件循環執行異步方法
asyncio.get_event_loop().run_until_complete(main())
怎么在js里打開文件
在里打開文件的核心操作包括:使用File API讀取本地文件、通過fetch API獲取遠程文件、以及通過Node.js的fs模塊處理服務器端文件。 在此,我們將詳細探討這三種方法中的一種:使用File API讀取本地文件。
一、使用File API讀取本地文件
1. 文件選擇器
要使用File API讀取本地文件,首先需要用戶選擇文件。通過HTML的標簽,可以創建一個文件選擇器。
2. 讀取文件內容
接下來,通過監聽文件選擇事件,并使用讀取文件內容。
document.getElementById('fileInput').addEventListener('change', function(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
console.log(e.target.result); // 讀取的文件內容
};
reader.readAsText(file); // 以文本形式讀取文件
}
});
對象 提供了幾種不同的方法來讀取文件內容,例如 , , 和 。其中 方法最常用于讀取文本文件。
二、使用fetch API獲取遠程文件
1. 基本用法
fetch API可以用于獲取遠程服務器上的文件內容。以下是一個示例:
fetch('https://example.com/file.txt')
.then(response => response.text())
.then(data => {
console.log(data); // 遠程文件內容
})
.catch(error => {
console.error('Error fetching the file:', error);
});
2. 錯誤處理
使用fetch API時,處理錯誤非常重要。可以通過catch方法捕獲并處理異常情況。
fetch('https://example.com/file.txt')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
三、使用Node.js的fs模塊處理服務器端文件
1. 導入fs模塊
在Node.js環境中,可以使用內置的fs模塊來讀取文件。首先需要導入這個模塊:
const fs = require('fs');
2. 讀取文件內容
使用fs.方法來異步讀取文件內容:
fs.readFile('path/to/file.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading the file:', err);
return;
}
console.log(data); // 文件內容

});
3. 同步讀取文件
如果需要同步讀取文件,可以使用fs.方法:
try {
const data = fs.readFileSync('path/to/file.txt', 'utf8');
console.log(data); // 文件內容
} catch (err) {
console.error('Error reading the file:', err);
}
四、使用Blob對象在瀏覽器中創建文件
1. 創建Blob對象
在瀏覽器中,也可以使用Blob對象創建一個文件,并通過URL.生成一個下載鏈接:
const data = new Blob(['Hello, world!'], { type: 'text/plain' });
const url = URL.createObjectURL(data);
const a = document.createElement('a');
a.href = url;
a.download = 'hello.txt';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
2. 銷毀URL對象
使用完URL對象后,應該調用URL.方法來釋放內存:
URL.revokeObjectURL(url);
五、使用第三方庫處理文件
1. .js
.js是一個常用的庫,用于在瀏覽器中保存文件。以下是一個示例:
import { saveAs } from 'file-saver';
const data = new Blob(['Hello, world!'], { type: 'text/plain' });
saveAs(data, 'hello.txt');
2. JSZip
JSZip是另一個常用的庫,用于在瀏覽器中創建和解壓縮ZIP文件。以下是一個示例:
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
const zip = new JSZip();
zip.file('hello.txt', 'Hello, world!');
zip.generateAsync({ type: 'blob' }).then(function(content) {
saveAs(content, 'example.zip');
});
六、文件操作的安全性與用戶體驗
1. 文件權限
在瀏覽器環境中,出于安全考慮,只能訪問用戶明確選擇的文件。無法直接訪問用戶的文件系統。
2. 用戶體驗
為了提升用戶體驗,可以使用文件選擇器進行文件操作,并提供清晰的指引和錯誤提示。例如:
document.getElementById('fileInput').addEventListener('change', function(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
console.log(e.target.result);
};
reader.onerror = function(e) {
console.error('Error reading the file:', e);
alert('Failed to read the file. Please try again.');
};
reader.readAsText(file);
} else {
alert('No file selected. Please choose a file.');
}
});
七、項目管理系統的集成
在研發項目管理中,文件操作經常涉及到文檔、配置文件和數據文件的管理。推薦使用以下兩個系統來實現更加高效的項目管理:
1. 研發項目管理系統
是一款專業的研發項目管理系統,提供了全面的文件管理功能。通過集成,可以實現文檔的集中管理和版本控制,提高團隊協作效率。
2. 通用項目協作軟件
是一款通用項目協作軟件,支持文件共享和管理。通過,可以輕松實現團隊成員之間的文件共享和協作,提升工作效率。
總結
在中打開文件可以通過多種方法實現,包括使用File API讀取本地文件、通過fetch API獲取遠程文件、以及通過Node.js的fs模塊處理服務器端文件。每種方法都有其適用的場景和優勢。在實際應用中,可以根據具體需求選擇合適的方法,并結合項目管理系統和,提高文件操作的效率和安全性。
相關問答FAQs:
1. 如何在中打開文件?
在中,要打開文件,可以使用對象。以下是一個簡單的示例代碼:
// 創建一個FileReader對象
var reader = new FileReader();
// 通過input元素選擇文件
var fileInput = document.getElementById('fileInput');
var file = fileInput.files[0];
// 讀取文件內容
reader.readAsText(file);
// 當文件讀取完成時觸發的事件
reader.onload = function(e) {
var contents = e.target.result;
console.log('文件內容:', contents);
};
2. 如何在中通過文件路徑打開文件?
在中,可以使用對象來通過文件路徑打開文件。以下是一個示例代碼:
// 創建一個XMLHttpRequest對象
var xhr = new XMLHttpRequest();
// 打開文件
xhr.open('GET', 'path/to/file.txt', true);
// 發送請求
xhr.send();
// 當請求完成時觸發的事件
xhr.onload = function() {
if (xhr.status === 200) {
var contents = xhr.responseText;
console.log('文件內容:', contents);
}
};
3. 如何在中通過URL打開文件?
在中,可以使用fetch函數來通過URL打開文件。以下是一個示例代碼:
// 通過URL打開文件
fetch('https://example.com/path/to/file.txt')
.then(function(response) {
return response.text();
})
.then(function(contents) {
console.log('文件內容:', contents);
})
.catch(function(error) {
console.log('發生錯誤:', error);
});
請注意,這些示例代碼僅供參考,具體實現方式可能因使用的框架或庫而有所不同。
*請認真填寫需求信息,我們會在24小時內與您取得聯系。