Python3讀取HTML檔案

2021-08-17 20:23:10 字數 1639 閱讀 4278

在學習《designing machine learning systems with python》(中文名《機器學習系統設計——python語言實現》)一書中,在第三章第二節第五小節(p68)讀取html文件資料的**中。我發現有些不太懂,就把學習過程記錄下來。

首先,如果你在python3.6環境中照搬書中的**的話,你會得到這樣乙個錯誤提示,修改方法可以看我之前的部落格。

attributeerror: module

'urllib' has no attribute 'request'

然後就可以正常執行了。

修改後**:

# import urllib

from urllib import request

from bs4 import beautifulsoup

import numpy as np

url = request.urlopen("")

html = url.read()

soup = beautifulsoup(html, 'lxml')

table = soup.find("table")

headings = [th.get_text() for th in table.find("tr").find_all("th")]

datasets =

for row in table.find_all("tr")[1:]:

dataset = list(zip(headings, (td.get_text() for td in row.find_all("td"))))

nd = np.array(datasets)

features = nd[:, 1:, 1].astype('float')

targets = (nd[:, 0, 1:]).astype('str')

print(features)

print(targets)

執行結果:

[[1. 1.]

[2. 2.]

[3. 3.]]

[['whitefly']

['thrip']

['aphid']]

我之所以寫這篇部落格的原因是我在學習這個**時,發現一些不太明白的地方。主要有兩點,乙個是在soup = beautifulsoup(html, 'lxml')這行**中,beautifulsoup()函式有兩個輸入,而我常見的都是只有乙個輸入,這裡的第二個引數我好奇到底是什麼;另乙個不太清楚的是beautifulsoup中find()和find_all()之間有什麼區別。

第二個問題很好解決,只要在網上搜下查下beautifulsoup的中文文件就能明白。find()只返回尋找到的第乙個匹配的引數,find_all()則返回文件中全部匹配的引數。

第乙個問題在找到的中文文件中剛開始沒有找到,後來在頁面的後邊找到了(汗(lll¬ω¬),第一次看的是由多不認真),第二個引數是指定對該文件的解析器的,可供選擇的解析器有

目前支援, 「lxml」, 「html5lib」, 和 「html.parser」

這個結果告訴我們看文件不要不耐煩,要認真。(逃ε=ε=ε=┏(゜ロ゜;)┛)

python 3讀取檔案 Python3 檔案讀寫

python open 方法用於開啟乙個檔案,並返回檔案物件,在對檔案進行處理過程都需要使用到這個函式 1.讀取檔案 with open test json dumps.txt mode r encoding utf 8 as f seek 移動游標至指定位置 f.seek 0 read 讀取整個檔...

Python3 讀取Word檔案

我的環境,windows10,python3.6.3 查詢了很多有關資料,發現都是python2版本操作word檔案的,所以就寫了這篇短小的文章。一 安裝 docx pip install docx 完了之後,匯入 import docx 發現報錯 modulenotfounderror no mo...

Python3 讀取大檔案

1 方法一 將檔案切分成小段,每次處理完小段內容後,釋放記憶體 這裡會使用yield生成自定義可迭代物件,即generator,每乙個帶有yield的函式就是乙個generator。def read in block file path block size 1024 with open file ...