[英]Reading and parsing HTML files starting from a specific line using Python
我有這個 Python 代碼,我正在嘗試改進以讀取和解析一些 HTML 文件,但我希望它從第 415 行開始。因為我想定位<div class="panel-body">
在哪里有我要解析的數據。 因為已經有另一個<div class="panel-body">
,但它不是我想要定位的正確對象。 這是我的代碼:
for filename in os.listdir(folder):
if filename.endswith('.html'):
fname = os.path.join(folder, filename)
print('Filename: {}'.format(fname))
with open (fname, 'r', encoding='utf8') as f:
soup = BeautifulSoup(f.read(), 'html.parser')
info = soup.find_all('div' ,class_= 'panel-body')
您可以提取從 415 開始到結束的行。 將此塊傳遞給BeautifulSoup
以從 HTML 中獲取數據。這是代碼。
from itertools import islice
from bs4 import BeautifulSoup
import os
fname = "TestFile"
folder = "TestFolder"
for filename in os.listdir(folder):
if filename.endswith('.html'):
fname = os.path.join(folder, filename)
print('Filename: {}'.format(fname))
with open (fname, 'r', encoding='utf8') as f:
block = islice(f, 415, 600)
for line in block:
soup = BeautifulSoup(line, 'html.parser')
info = soup.find_all('div', class_='panel-body')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.