PHP前端开发

request库爬虫是什么?

百变鹏仔 3小时前 #Python
文章标签 爬虫

request库爬虫是什么?如何使用?本篇文章给大家带来的内容是介绍request库爬虫是什么?如何使用?通过实例讲解。有一定的参考价值,有需要的朋友可以参考一下,希望对你们有所帮助。

利用request.get()返回response对象爬出单个京东页面信息

import requestsurl = "https://item.jd.com/21508090549.html"try:r = requests.get(url)r.raise_for_status()          #检验http状态码是否为200r.encoding = r.apparent_encoding#识别页面正确编码print(r.text[:1000])except:print("爬取失败")

 如果用上面的代码访问亚马逊页面,就会爬取到错误信息,因为亚马逊robots协议中定义了不允许非主流浏览器对页面进行访问,所以要对request访问信息中的‘user-agent’设置

import requestsurl = "https://www.amazon.cn/gp/product/B01M8L5Z3Y"try:#kv = {'user-agent':'Mozilla/5.0'}#假装访问浏览器为Mozilla/5.0r = requests.get(url)r.raise_for_status()#检验http状态码是否为200r.encoding = r.apparent_encoding#识别页面正确编码print(r.text[:1000])except:print("爬取失败")

 利用代码模仿百度/360搜索

需要在url上添加参数百度的'wd=..'/360是'q=...'

import requestsurl = "http://www.baidu.com/s"keyword="python"try:kv = {'wd':key}r = requests.get(url,params=kv)print(r.request.url)r.raise_for_status()#检验http状态码是否为200r.encoding = r.apparent_encoding#识别页面正确编码print(len(r.text))#由于信息量可能特别大,这里只输出长度except:print("爬取失败")

 爬取并保存图片

import requestsimport osurl = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1540201265460&di=64720dcd3bbc24b7d855454028173deb&imgtype=0&src=http%3A%2F%2Fpic34.photophoto.cn%2F20150105%2F0005018358919011_b.jpg"root = "D://pics//"path = root + url.split('.')[-2]+'.'+url.split('.')[-1]#得到文件名,生成文件路径if not os.path.exists(root):os.mkdir(root)#如果目录不存在,创建目录if not os.path.exists(path):#如果文件不存在爬取文件并保存r = requests.get(url)with open(path,'wb') as f:#打开文件对象	f.write(r.content)#写入爬取的图片	f.close()	print("文件保存成功")else:print("文件已存在")

 总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。更多相关教程请访问C#视频教程!