10个python爬虫入门基础代码实例 + 1个简单的python爬虫完整实例

本文主要涉及python爬虫知识点:

web是如何交互的

requests库的get、post函数的应用

response对象的相关函数,属性

python文件的打开,保存

代码中给出了注释,并且可以直接运行哦

如何安装requests库(安装好python的朋友可以直接参考,没有的,建议先装一哈python环境)

windows用户,Linux用户几乎一样:

打开cmd输入以下命令即可,如果python的环境在C盘的目录,会提示权限不够,只需以管理员方式运行cmd窗口

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests

Linux用户类似(ubantu为例): 权限不够的话在命令前加入sudo即可

sudo pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests

python爬虫入门基础代码实例如下

1.Requests爬取BD页面并打印页面信息

# 第一个爬虫示例,爬取百度页面
import requests #导入爬虫的库,不然调用不了爬虫的函数
response = requests.get("http://www.baidu.com") #生成一个response对象
response.encoding = response.apparent_encoding #设置编码格式
print("状态码:"+ str( response.status_code ) ) #打印状态码
print(response.text)#输出爬取的信息

2.Requests常用方法之get方法实例,下面还有传参实例

# 第二个get方法实例
import requests #先导入爬虫的库,不然调用不了爬虫的函数
response = requests.get("http://httpbin.org/get") #get方法
print( response.status_code ) #状态码
print( response.text )

3. Requests常用方法之post方法实例,下面还有传参实例

# 第三个 post方法实例
import requests #先导入爬虫的库,不然调用不了爬虫的函数
response = requests.post("http://httpbin.org/post") #post方法访问
print( response.status_code ) #状态码
print( response.text )

4. Requests put方法实例

# 第四个 put方法实例
import requests #先导入爬虫的库,不然调用不了爬虫的函数
response = requests.put("http://httpbin.org/put") # put方法访问
print( response.status_code ) #状态码
print( response.text )

5.Requests常用方法之get方法传参实例(1)

如果需要传多个参数只需要用&符号连接即可如下

# 第五个 get传参方法实例
import requests #先导入爬虫的库,不然调用不了爬虫的函数
response = requests.get("http://httpbin.org/get?name=hezhi&age=20") # get传参
print( response.status_code ) #状态码
print( response.text )

6.Requests常用方法之get方法传参实例(2)

params用字典可以传多个

# 第六个 get传参方法实例
import requests #先导入爬虫的库,不然调用不了爬虫的函数
data = {
	"name":"hezhi",
	"age":20
}
response = requests.get( "http://httpbin.org/get" , params=data ) # get传参
print( response.status_code ) #状态码
print( response.text )

7.Requests常用方法之post方法传参实例(2) 和上一个有没有很像

# 第七个 post传参方法实例
import requests #先导入爬虫的库,不然调用不了爬虫的函数
data = {
	"name":"hezhi",
	"age":20
}
response = requests.post( "http://httpbin.org/post" , params=data ) # post传参
print( response.status_code ) #状态码
print( response.text )

8.关于绕过反爬机制,以知呼为例

# 第好几个方法实例
import requests #先导入爬虫的库,不然调用不了爬虫的函数
response = requests.get( "http://www.zhihu.com") #第一次访问知乎,不设置头部信息
print( "第一次,不设头部信息,状态码:"+response.status_code )# 没写headers,不能正常爬取,状态码不是 200
#下面是可以正常爬取的区别,更改了User-Agent字段
headers = {
		"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36"
}#设置头部信息,伪装浏览器
response = requests.get( "http://www.zhihu.com" , headers=headers ) #get方法访问,传入headers参数,
print( response.status_code ) # 200!访问成功的状态码
print( response.text )

9.爬取信息并保存到本地

因为目录关系,在D盘建立了一个叫做爬虫的文件夹,然后保存信息

注意文件保存时的encoding设置

# 爬取一个html并保存
import requests
url = "http://www.baidu.com"
response = requests.get( url )
response.encoding = "utf-8" #设置接收编码格式
print("\nr的类型" + str( type(response) ) )
print("\n状态码是:" + str( response.status_code ) )
print("\n头部信息:" + str( response.headers ) )
print( "\n响应内容:" )
print( response.text )

#保存文件
file = open("D:\\爬虫\\baidu.html","w",encoding="utf") #打开一个文件,w是文件不存在则新建一个文件,这里不用wb是因为不用保存成二进制
file.write( response.text )
file.close()

10.爬取图片,保存到本地

#保存百度图片到本地
import requests #先导入爬虫的库,不然调用不了爬虫的函数
response = requests.get("https://www.baidu.com/img/baidu_jgylogo3.gif") #get方法的到图片响应
file = open("D:\\爬虫\\baidu_logo.gif","wb") #打开一个文件,wb表示以二进制格式打开一个文件只用于写入
file.write(response.content) #写入文件
file.close()#关闭操作,运行完毕后去你的目录看一眼有没有保存成功

下面是一个完整的python爬虫实例,功能是爬取百度贴吧上的图片并下载到本地;

你也可以关注公众号 Python客栈 回复 756 获取完整代码;


扫描上面二维码关注公众号 Python客栈 回复 756 获取完整python爬虫源码

python爬虫主要操作步骤:

获取网页html文本内容;

分析html中图片的html标签特征,用正则解析出所有的图片url链接列表;

根据图片的url链接列表将图片下载到本地文件夹中。

1. urllib+re实现

#!/usr/bin/python
# coding:utf-8
# 实现一个简单的爬虫,爬取百度贴吧图片
import urllib
import re

# 根据url获取网页html内容
def getHtmlContent(url):
  page = urllib.urlopen(url)
  return page.read()

# 从html中解析出所有jpg图片的url
# 百度贴吧html中jpg图片的url格式为:<img ... src="XXX.jpg" width=...>
def getJPGs(html):
  # 解析jpg图片url的正则
  jpgReg = re.compile(r'<img.+?src="(.+?\.jpg)" width') # 注:这里最后加一个'width'是为了提高匹配精确度
  # 解析出jpg的url列表
  jpgs = re.findall(jpgReg,html)

  return jpgs

# 用图片url下载图片并保存成制定文件名
def downloadJPG(imgUrl,fileName):
  urllib.urlretrieve(imgUrl,fileName)

# 批量下载图片,默认保存到当前目录下
def batchDownloadJPGs(imgUrls,path = './'):
  # 用于给图片命名
  count = 1
  for url in imgUrls:
    downloadJPG(url,''.join([path,'{0}.jpg'.format(count)]))
    count = count + 1

# 封装:从百度贴吧网页下载图片
def download(url):
  html = getHtmlContent(url)
  jpgs = getJPGs(html)
  batchDownloadJPGs(jpgs)

def main():
  url = 'http://tieba.baidu.com/p/2256306796'
  download(url)

if __name__ == '__main__':
  main()

运行上面脚本,过几秒种之后完成下载,可以在当前目录下看到图片已经下载好了:

2. requests + re实现

下面用requests库实现下载,把getHtmlContent和downloadJPG函数都用requests重新实现。

#!/usr/bin/python
# coding:utf-8
# 实现一个简单的爬虫,爬取百度贴吧图片
import requests
import re

# 根据url获取网页html内容
def getHtmlContent(url):
  page = requests.get(url)
  return page.text

# 从html中解析出所有jpg图片的url
# 百度贴吧html中jpg图片的url格式为:<img ... src="XXX.jpg" width=...>
def getJPGs(html):
  # 解析jpg图片url的正则
  jpgReg = re.compile(r'<img.+?src="(.+?\.jpg)" width') # 注:这里最后加一个'width'是为了提高匹配精确度
  # 解析出jpg的url列表
  jpgs = re.findall(jpgReg,html)

  return jpgs

# 用图片url下载图片并保存成制定文件名
def downloadJPG(imgUrl,fileName):
  # 可自动关闭请求和响应的模块
  from contextlib import closing
  with closing(requests.get(imgUrl,stream = True)) as resp:
    with open(fileName,'wb') as f:
      for chunk in resp.iter_content(128):
        f.write(chunk)

# 批量下载图片,默认保存到当前目录下
def batchDownloadJPGs(imgUrls,path = './'):
  # 用于给图片命名
  count = 1
  for url in imgUrls:
    downloadJPG(url,''.join([path,'{0}.jpg'.format(count)]))
    print '下载完成第{0}张图片'.format(count)
    count = count + 1

# 封装:从百度贴吧网页下载图片
def download(url):
  html = getHtmlContent(url)
  jpgs = getJPGs(html)
  batchDownloadJPGs(jpgs)

def main():
  url = 'http://tieba.baidu.com/p/2256306796'
  download(url)

if __name__ == '__main__':
  main()

上面介绍的10个python爬虫入门基础代码实例和1个简单的python爬虫完整实例虽然都是基础知识但python爬虫的主要操作方法也是这些,掌握这些python爬虫就学会一大半了。更多关于python爬虫的文章请查看下面的相关罗拉

(0)

相关推荐

  • python爬虫基础教程:requests库(二)代码实例

    get请求 简单使用 import requests ''' 想要学习Python?Python学习交流群:973783996满足你的需求,资料都已经上传群文件,可以自行下载! ''' response = requests.get("https://www.baidu.com/") #text返回的是unicode的字符串,可能会出现乱码情况 # print(response.text) #content返回的是字节,需要解码 print(response.content.decod

  • python爬虫开发之使用Python爬虫库requests多线程抓取猫眼电影TOP100实例

    使用Python爬虫库requests多线程抓取猫眼电影TOP100思路: 查看网页源代码 抓取单页内容 正则表达式提取信息 猫眼TOP100所有信息写入文件 多线程抓取 运行平台:windows Python版本:Python 3.7. IDE:Sublime Text 浏览器:Chrome浏览器 1.查看猫眼电影TOP100网页原代码 按F12查看网页源代码发现每一个电影的信息都在"<dd></dd>"标签之中. 点开之后,信息如下: 2.抓取单页内容 在浏

  • python爬虫开发之使用python爬虫库requests,urllib与今日头条搜索功能爬取搜索内容实例

    使用python爬虫库requests,urllib爬取今日头条街拍美图 代码均有注释 import re,json,requests,os from hashlib import md5 from urllib.parse import urlencode from requests.exceptions import RequestException from bs4 import BeautifulSoup from multiprocessing import Pool #请求索引页 d

  • python爬虫 基于requests模块的get请求实现详解

    需求:爬取搜狗首页的页面数据 import requests # 1.指定url url = 'https://www.sogou.com/' # 2.发起get请求:get方法会返回请求成功的响应对象 response = requests.get(url=url) # 3.获取响应中的数据:text属性作用是可以获取响应对象中字符串形式的页面数据 page_data = response.text # 4.持久化数据 with open("sougou.html","w&

  • 使用requests库制作Python爬虫

    使用python爬虫其实就是方便,它会有各种工具类供你来使用,很方便.Java不可以吗?也可以,使用httpclient工具.还有一个大神写的webmagic框架,这些都可以实现爬虫,只不过python集成工具库,使用几行爬取,而Java需要写更多的行来实现,但目的都是一样. 下面介绍requests库简单使用: #!/usr/local/env python # coding:utf-8 import requests #下面开始介绍requests的使用,环境语言是python3,使用下面的

  • python爬虫使用requests发送post请求示例详解

    简介 HTTP协议规定post提交的数据必须放在消息主体中,但是协议并没有规定必须使用什么编码方式.服务端通过是根据请求头中的Content-Type字段来获知请求中的消息主体是用何种方式进行编码,再对消息主体进行解析.具体的编码方式包括: application/x-www-form-urlencoded 最常见post提交数据的方式,以form表单形式提交数据. application/json 以json串提交数据. multipart/form-data 一般使用来上传文件. 一. 以f

  • 使用Python爬虫库requests发送表单数据和JSON数据

    导入Python爬虫库Requests import requests 一.发送表单数据 要发送表单数据,只需要将一个字典传递给参数data payload = {'key1': 'value1', 'key2': 'value2'} r = requests.post("http://httpbin.org/post", data=payload) print(r.text) {"args":{},"data":"",&qu

  • python爬虫 基于requests模块发起ajax的get请求实现解析

    基于requests模块发起ajax的get请求 需求:爬取豆瓣电影分类排行榜 https://movie.douban.com/中的电影详情数据 用抓包工具捉取 使用ajax加载页面的请求 鼠标往下下滚轮拖动页面,会加载更多的电影信息,这个局部刷新是当前页面发起的ajax请求, 用抓包工具捉取页面刷新的ajax的get请求,捉取滚轮在最底部时候发起的请求 这个get请求是本次发起的请求的url ajax的get请求携带参数 获取响应内容不再是页面数据,是json字符串,是通过异步请求获取的电影

  • Python爬虫库requests获取响应内容、响应状态码、响应头

    首先在程序中引入Requests模块 import requests 一.获取不同类型的响应内容 在发送请求后,服务器会返回一个响应内容,而且requests通常会自动解码响应内容 1.文本响应内容 获取文本类型的响应内容 r = requests.get('https://www.baidu.com') r.text # 通过文本的形式获取响应内容 '<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><m

  • python爬虫入门教程--利用requests构建知乎API(三)

    前言 在爬虫系列文章 优雅的HTTP库requests中介绍了 requests 的使用方式,这一次我们用 requests 构建一个知乎 API,功能包括:私信发送.文章点赞.用户关注等,因为任何涉及用户操作的功能都需要登录后才操作,所以在阅读这篇文章前建议先了解Python模拟知乎登录 .现在假设你已经知道如何用 requests 模拟知乎登录了. 思路分析 发送私信的过程就是浏览器向服务器发送一个 HTTP 请求,请求报文包括请求 URL.请求头 Header.还有请求体 Body,只要把

  • Python爬虫工具requests-html使用解析

    使用Python开发的同学一定听说过Requsts库,它是一个用于发送HTTP请求的测试.如比我们用Python做基于HTTP协议的接口测试,那么一定会首选Requsts,因为它即简单又强大.现在作者Kenneth Reitz 又开发了requests-html 用于做爬虫. 该项目从3月上线到现在已经7K+的star了! GiHub项目地址: https://github.com/kennethreitz/requests-html requests-html 是基于现有的框架 PyQuery

  • python爬虫入门教程--优雅的HTTP库requests(二)

    前言 urllib.urllib2.urllib3.httplib.httplib2 都是和 HTTP 相关的 Python 模块,看名字就觉得很反人类,更糟糕的是这些模块在 Python2 与 Python3 中有很大的差异,如果业务代码要同时兼容 2 和 3,写起来会让人崩溃. 好在,还有一个非常惊艳的 HTTP 库叫 requests,它是 GitHUb 关注数最多的 Python 项目之一,requests 的作者是 Kenneth Reitz 大神. requests 实现了 HTTP

  • 使用Python爬虫库requests发送请求、传递URL参数、定制headers

    首先我们先引入requests模块 import requests 一.发送请求 r = requests.get('https://api.github.com/events') # GET请求 r = requests.post('http://httpbin.org/post', data = {'key':'value'}) # POST请求 r = requests.put('http://httpbin.org/put', data = {'key':'value'}) # PUT请

随机推荐