数据爬取之基本概念

初识HTML

这一块我也是新手,html是一种用来描述网页的语言,也叫超文本标记语言,就是我们肉眼所看到经过浏览器解释的网页,实际背后是用html书写的文本。其中关键是html标记标签,如,一般这种标签由正反尖括号组成,里面是关键词,成对出现,代表该关键词的开始位置和结束位置,一般我们爬取数据只要找到所需关键词标签,然后截取出来即可,太细节的事可能需要前端知识来解释,以后慢慢修正。下面由网上的小实例练练手。

# -*- coding: utf-8 -*-
#首先要导入urlib.request库,还有很多打开URL的库,大家可以尝试
import urllib.request
#用该库的urlopen函数打开目标网页
response = urllib.request.urlopen(r'file:///Users/herenyi/Downloads/6/6.1/html.html')
#然后read属性读取源代码
html = response.read();
#很简单的一个练手html,\r是回车的意思(回到该行行首),\n是换行的意思(跳到下一行用列),\t是一个tab健
html
b'<html>\r\n\t<body>\r\n\t\t<table>\r\n\t\t\t<tr><td>name</td><td>age</td></tr>\r\n\t\t\t<tr><td>Ken</td><td>28</td></tr>\r\n\t\t\t<tr><td>John</td><td>30</td></tr>\r\n\t\t</table>\r\n\t</body>\r\n</html>\r\n'

读取网页完成后,就轮到Beatifulsoup来大显身手了

from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
soup
Out[197]: 
<html>
<body>
<table>
<tr><td>name</td><td>age</td></tr>
<tr><td>Ken</td><td>28</td></tr>
<tr><td>John</td><td>30</td></tr>
</table>
</body>
</html>#界面是不是清洁很多了
#找到所有带tr关键词的标记标签
soup.find_all('tr')
Out[199]: 
[<tr><td>name</td><td>age</td></tr>,
 <tr><td>Ken</td><td>28</td></tr>,
 <tr><td>John</td><td>30</td></tr>]

初识JSON

JSON是一种轻量级的数据交换格式,全称——JavaScript 对象表示法(JavaScript Object Notation)。看着意思貌似是Javascript的一个数据格式,先试着敲一遍,背后细节以后有空在研究。

#照样是导入读取库读取然后使用read属性
import urllib.request;
response = urllib.request.urlopen(r'file:///Users/herenyi/Downloads/6/6.2/json.json');
jsonString = response.read();
#读取后的源代码是这样的
jsonString
Out[202]: b'{\r\n\t"employees": [\r\n\t\t{ "firstName":"Bill" , "lastName":"Gates" },\r\n\t\t{ "firstName":"George" , "lastName":"Bush" },\r\n\t\t{ "firstName":"Thomas" , "lastName":"Carter" }\r\n\t]\r\n}\r\n'
#然后倒入json库
import json
#用json库里的loads函数重新编码
jsonObject = json.loads(jsonString.decode())
#重新编码后的样子
jsonObject
Out[206]: 
{'employees': [{'firstName': 'Bill', 'lastName': 'Gates'},
  {'firstName': 'George', 'lastName': 'Bush'},
  {'firstName': 'Thomas', 'lastName': 'Carter'}]}
  #然后就可以跟普通的字典一样随意调取了

jsonObject
Out[206]: 
{'employees': [{'firstName': 'Bill', 'lastName': 'Gates'},
  {'firstName': 'George', 'lastName': 'Bush'},
  {'firstName': 'Thomas', 'lastName': 'Carter'}]}

jsonObject['employees']
Out[207]: 
[{'firstName': 'Bill', 'lastName': 'Gates'},
 {'firstName': 'George', 'lastName': 'Bush'},
 {'firstName': 'Thomas', 'lastName': 'Carter'}]

jsonObject['employees'][0]
Out[208]: {'firstName': 'Bill', 'lastName': 'Gates'}

jsonObject['employees'][0]['lastName']
Out[209]: 'Gates'

初识爬虫

爬虫是什么,爬虫就是借用工具来爬取网站数据的程序。
爬虫设计的一般思路:

  1. 首先要确定需要爬取网页的URL地址
  2. 通过Http协议来获取对应的HTML页面
  3. 提取HTML页面里有用的数据并保存
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值