http协议:
常用请求头:
User-Agent:请求载体的身份标识
Connection:请求完毕后是断开还是保持连接
常用响应头:
Content-Type:服务器响应回客户端的数据类型
https协议:采用证书加密
resquests模块:
作用:模拟浏览器发送请求。
使用:requests模块的编码流程
-指定url
-发起请求(GET\POST)
-获取相应数据
-持久化存储
反爬机制
UA检测
——UA伪装:User-Agent
数据解析
聚焦爬虫:爬取页面中指定的内容。
——编码流程
——指定url
——发起请求(GET\POST)
——获取相应数据
——数据解析
——持久化存储
数据解析分类:
——正则
——bs4
——xpath(重要)
数据解析原理:
——解析的局部文本内容都会在标签之间或者是标签对应的属性中进行存储
——1.进行指定标签的定位
——2.对标签之间或者标签对应的属性中存储的数据值进行提取(解析)
xpath表达式
/:表示一个层级,放前面表示从根节点定位
//:表示多个层级,放前面表示从任意节点开始定位
属性定位:tag[@attrName="attrValue"],例如//div[@class="song"]
索引定位:用[],从1开始索引。例如//div[@class="song"]/p[3]
取文本:/text() :直系文本内容
//text(): 全部文本内容
取属性:/@属性,例如/img/@src
注意:./表示当前标签。
xpath()返回的是列表,要用[0]来索引为内容
爬了一下58同城的二手房源信息,代码如下
import requests
from lxml import etree
headers = {
"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.57"
}
url = "https://hz.58.com/ershoufang/"
page_text = requests.get(url=url,headers=headers).text
tree = etree.HTML(page_text)
div_list = tree.xpath('//div[@class="property"]')
fp = open("58ershoufang.txt","w",encoding="utf-8")
for div in div_list:
title = div.xpath('./a//div[@class="property-content-title"]/h3//text()')[0]
price = div.xpath('./a//p[@class="property-price-total"]//text()')[0] + div.xpath('./a//p[@class="property-price-total"]//text()')[2]
print('title:'+title+ ' '*10 +'price:'+price)
fp.write('title:'+title+ ' '*10 +'price:'+price+'\n' )
fp.close()
出现乱码后处理的办法:
1.
response = requests.get(...)
response.encoding = 'utf-8'
2.
#较为通用的解决方案,在乱码发生的地方
img_name = li.xpath('./a/img/@alt')[0]+'.jpg'
img_name = img_name.encode('iso-8859-1').decode('gbk')
创建文件夹操作:
#创建文件夹
if not os.path.exists('./picLibs'):
os.mkdir('./picLibs')