【发布时间】:2018-02-26 05:30:53
【问题描述】:
我是 python 新手,如果我的问题非常基本,我很抱歉。在我的程序中,我需要解析一个 html 网页并提取其中的所有链接。假设我的网页内容如下:
<html><head><title>Fakebook</title><style TYPE="text/css"><!--
#pagelist li { display: inline; padding-right: 10px; }
--></style></head><body><h1>testwebapp</h1><p><a href="/testwebapp/">Home</a></p><hr/><h1>Welcome to testwebapp</h1><p>Random URLs!</p><ul><li><a href="/testwebapp/847945358/">Rennie Tach</a></li><li><a href="/testwebapp/848854776/">Pid Ko</a></li><li><a href="/testwebapp/850558104/">Ler She</a></li><li><a href="/testwebapp/851635068/">iti Sar</a></li><li><a </ul>
<p>Page 1 of 2
<ul id="pagelist"><li>
1
</li><li><a href="/testwebapp/570508160/fri/2/">2</a></li><li><a href="/testwebapp/570508160/fri/2/">next</a></li><li><a href="/testwebapp/570508160/fri/2/">last</a></li></ul></p>
</body></html>
现在,我需要解析这个网页内容并提取其中的所有链接。换句话说,我需要从网页中提取以下内容:
/testwebapp/847945358/
/testwebapp/848854776/
/testwebapp/850558104/
/testwebapp/851635068/
/testwebapp/570508160/fri/2/
/testwebapp/570508160/fri/2/
/testwebapp/570508160/fri/2/
我搜索了很多关于使用 python 解析网页的信息,例如 this、this 或 this,但其中许多人使用了 urlib 或 urlib2 或 BeautifulSoup 等库,并请求我不能使用这些库在我的程序中。因为我的应用程序将在尚未安装这些库的机器上运行。所以我需要手动解析我的网页内容。我的想法是,我将网页内容保存在一个字符串中,然后将字符串((由空格分隔))转换为字符串数组,然后检查我的数组的每个项目,如果它有 /testwebapp/ 或 @987654327 @ 关键字,将其保存在数组中。但是当我使用下面的命令将包含我的网页内容的字符串转换为数组时,我收到了这个错误:
arrayofwords_fromwebpage = (webcontent_saved_in_a_string).split(" ")
错误是:
TypeError: a bytes-like object is required, not 'str'
是否有任何快速有效的方法可以在不使用任何库(如 urlib、urlib2 或 BeautifulSoup)的情况下解析和提取 html 网页中的此链接?
【问题讨论】:
标签: python html arrays string html-parsing