Python3读取HTML文件

在学习《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("http://interthing.org/dmls/species.html")
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"))))
    datasets.append(dataset)

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,html,机器学习系统实现)