当前位置:Gxlcms > Python > request库爬虫是什么?如何使用?(实例讲解)

request库爬虫是什么?如何使用?(实例讲解)

时间:2021-07-01 10:21:17 帮助过:97人阅读

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

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

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

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

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

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

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

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

爬取并保存图片

  1. import requests
  2. import os
  3. url = "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"
  4. root = "D://pics//"
  5. path = root + url.split('.')[-2]+'.'+url.split('.')[-1]#得到文件名,生成文件路径
  6. if not os.path.exists(root):
  7. os.mkdir(root)#如果目录不存在,创建目录
  8. if not os.path.exists(path):#如果文件不存在爬取文件并保存
  9. r = requests.get(url)
  10. with open(path,'wb') as f:#打开文件对象
  11. f.write(r.content)#写入爬取的图片
  12. f.close()
  13. print("文件保存成功")
  14. else:
  15. print("文件已存在")

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

以上就是request库爬虫是什么?如何使用?(实例讲解)的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行