Python爬虫学习3
信息组织与提取方法
信息标记的种类
XML
JSON
YAML
三种信息标记的比较
基于bs4库的HTML内容查找方法
实例:提取HTML中的所有URL链接
以demo.html为例
思路:
- 搜索到所有<a>标签
- 解析<a>标签格式,提取href后面的内容
import requests
from bs4 import BeautifulSoup
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
soup = BeautifulSoup(demo, "html.parser")
for link in soup.find_all('a'):
print(link.get('href'))
bs4库中的find_all()方法
实战:基于bs4库爬取大学排名
目标:爬取最好大学网中的软科中国最好大学排名2016网页中的排名信息(网址:http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html)
import requests
from bs4 import BeautifulSoup
import bs4
def getHTMLText(url):
try:
r = requests.get(url)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
def fillUnivList(ulist, html):
soup = BeautifulSoup(html,"html.parser")
for tr in soup.find('tbody').children:
if isinstance(tr, bs4.element.Tag):
tds = tr('td')
ulist.append([tds[0].string, tds[1].string, tds[3].string])
pass
def printUnivList(ulist, num):
# print("{:^10}\t{:^6}\t{:^10}".format("排名","学校名称","总分"))
tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"
print(tplt.format("排名","学校名称","总分",chr(12288)))
for i in range(num):
u=ulist[i]
print(tplt.format(u[0],u[1],u[2],chr(12288)))
# print("{:^10}\t{:^6}\t{:^10}".format(u[0], u[1], u[2]))
def main():
uinfo = []
url = "http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html"
html = getHTMLText(url)
fillUnivList(uinfo, html)
printUnivList(uinfo, 20) # 20 univ
main()
最终的效果如下: