3.爬虫的具体步骤
1.需要数据对应的真实URL地址
2.找到对应的请求方式
3.使用第三方包,构造请求(注意需要进行伪装,headers的伪装,最重要的是需要进行浏览器伪装——User-Agent)
4发送请求
5.收到响应之后,需要对响应体数据进行解析(普通的页面text,如果是多媒体文件是content)
6.将拿到的页面或者多媒体文件按照需求进行提取(正则,Xpath等)
7..将获取到的目标文件进行保存
4.Xpath学习
4.1 html和xml的区别
xml不是html的替代,他们是为了不同的目的而设计的
xml被设计为传输和存储数据,其焦点是数据的内容
html被设计用来显示数据,其焦点是数据的外观
html重点在显示信息,而xml重点在传输信息
4.2 xml实例
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
例子中的根元素是 <bookstore>。文档中的所有 <book> 元素都被包含在 <bookstore> 中。<book> 元素有 4 个子元素:<title>、< author>、<year>、<price>。
4.3 路径表达
表达式 | 说明 |
---|---|
/ | 代表从根节点选取 |
// | 从当前文档的任何位置找起,只要符合节点就行 |
@ | 选取的是属性 |
. | 当前节点 |
… | 当前节点的父节点 |
4.4 xpath—etree的作用
str1 = '''
<div>this is a div
'''
doc = etree.HTML(str1)
str2 = etree.tostring(doc)
print(str2)
展示:
b'<html><body><div>this is a div\n</div></body></html>'
注意点:
1、tostring()转换的字符串是bytes类型
2、lxml可以补齐缺失的HTML标签,还可以自动添加html 和 body标签
4.5 获取标签内数据
ret = html_doc.xpath('//span/i/text()')
print(ret)
注意点:
1、text()获取标签扩起来的内容
2、xpath返回的数据类型是一个列表