1. Python3 使用urllib库请求网络

1.1 基于urllib库的GET请求

请求百度首页www.baidu.com ,不添加请求头信息:

 import urllib.requests

 def get_page():
5   url = 'http://www.baidu.com/'
  res = urllib.request.urlopen(url=url)
  page_source = res.read().decode('utf-8')
  print(page_source) if __name__ == '__main__':
  get_page()

输出显示百度首页的源码。但是有的网站进行了反爬虫设置,上述代码可能会返回一个40X之类的响应码,因为该网站识别出了是爬虫在访问网站,这时需要伪装一下爬虫,让爬虫模拟用户行为,给爬虫设置headers(User-Agent)属性,模拟浏览器请求网站。

1.2 使用User-Agent伪装后请求网站

由于urllib.request.urlopen() 函数不接受headers参数,所以需要构建一个urllib.request.Request对象来实现请求头的设置:

 import urllib.request

 def get_page():
5   url = 'http://www.baidu.com'
  headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
  }
9   request = urllib.request.Request(url=url, headers=headers)
  res = urllib.request.urlopen(request)
11   page_source = res.read().decode('utf-8')
  print(page_source) if __name__ == '__main__':
  get_page()

添加headers参数,来模拟浏览器的行为。

1.3 基于urllib库的POST请求,并用Cookie保持会话

登陆ChinaUnix论坛,获取首页源码,然后访问一个文章。首先不使用Cookie看一下什么效果:

 import urllib.request
import urllib.parse def get_page():
  url = 'http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LcN2z'
7   headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
  }
  data = {
    'username': 'StrivePy',
    'password': 'XXX'
  }
  postdata = urllib.parse.urlencode(data).encode('utf-8')
  req = urllib.request.Request(url=url, data=postdata, headers=headers)
  res = urllib.request.urlopen(req)
  page_source = res.read().decode('gbk')
18   print(page_source)   url1 = 'http://bbs.chinaunix.net/thread-4263876-1-1.html'
  res1 = urllib.request.urlopen(url=url1)
  page_source1 = res1.read().decode('gbk')
  print(page_source1) if __name__ == '__main__':
  get_page()

搜索源码中是否能看见用户名StrivePy,发现登陆成功,但是再请求其它文章时,显示为游客状态,会话状态没有保持。现在使用Cookie看一下效果:

 import urllib.request
import urllib.parse
import http.cookiejar def get_page():
  url = 'http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LcN2z'
  headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
  }
  data = {
    'username': 'StrivePy',
    'password': 'XXX'
  }
  postdata = urllib.parse.urlencode(data).encode('utf-8')
  req = urllib.request.Request(url=url, data=postdata, headers=headers)
  # 创建CookieJar对象
  cjar = http.cookiejar.CookieJar()
  # 以CookieJar对象为参数创建Cookie
  cookie = urllib.request.HTTPCookieProcessor(cjar)
  # 以Cookie对象为参数创建Opener对象
  opener = urllib.request.build_opener(cookie)
23   # 将Opener安装位全局,覆盖urlopen函数,也可以临时使用opener.open()函数
24   urllib.request.install_opener(opener)
  res = urllib.request.urlopen(req)
  page_source = res.read().decode('gbk')
  print(page_source)   url1 = 'http://bbs.chinaunix.net/thread-4263876-1-1.html'
  res1 = urllib.request.urlopen(url=url1)
  page_source1 = res1.read().decode('gbk')
  print(page_source1) if __name__ == '__main__':
  get_page()

结果显示登陆成功后,再访问其它文章时,显示为登陆状态。若要将Cookie保存为文件待下次使用,可以使用MozillaCookieJar对象将Cookie保存为文件。

 import urllib.request
import urllib.parse
import http.cookiejar def get_page():
url = 'http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LcN2z'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
}
data = {
'username': 'StrivePy',
'password': 'XXX'
}
postdata = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url=url, data=postdata, headers=headers)
filename = 'cookies.txt'
# 创建CookieJar对象
cjar = http.cookiejar.MozillaCookieJar(filename)
# 以CookieJar对象为参数创建Cookie
cookie = urllib.request.HTTPCookieProcessor(cjar)
# 以Cookie对象为参数创建Opener对象
opener = urllib.request.build_opener(cookie)
# 临时使用opener来请求
opener.open(req)
# 将cookie保存为文件
cjar.save(ignore_discard=True, ignore_expires=True)

会在当前工作目录生成一个名为cookies.txtcookie文件,下次就可以不用登陆(如果cookie没有失效的话)直接读取这个文件来实现免登录访问。例如不进行登陆直接访问其中一篇文章(没登陆也可以访问,主要是看抬头是不是登陆状态):

 import http.cookiejar

 def get_page():
url1 = 'http://bbs.chinaunix.net/thread-4263876-1-1.html'
filename = 'cookies.txt'
cjar = http.cookiejar.MozillaCookieJar(filename)
cjar.load(ignore_discard=True, ignore_expires=True)
cookie = urllib.request.HTTPCookieProcessor(cjar)
opener = urllib.request.build_opener(cookie)
res1 = opener.open(url1)
page_source1 = res1.read().decode('gbk')
print(page_source1) if __name__ == '__main__':
get_page()

结果显示是以登陆状态在查看这篇文章。

1.4 基于urllib库使用代理请求

使用代理可以有效规避爬虫被封。

 import urllib.request

 def proxy_test():
url = 'http://myip.kkcha.com/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
}
request = urllib.request.Request(url=url, headers=headers)
proxy = {
'http': '180.137.232.101:53281'
}
# 创建代理Handler对象
proxy_handler = urllib.request.ProxyHandler(proxy)
# 以Handler对象为参数创建Opener对象
opener = urllib.request.build_opener(proxy_handler)
# 将Opener安装为全局
urllib.request.install_opener(opener)
response = urllib.request.urlopen(request)
page_source = response.read().decode('utf-8')
print(page_source) if __name__ == '__main__':
proxy_test()

抓取到的页面应该显示代理IP,不知道什么原因,有时候能正常显示,有时候跳转到有道词典广告页!!!问题有待更进一步研究。

2. Python3 使用requsets库访问网络

2.1 基于requests库的GET请求

GET方式请求http://httpbin.org测试网站。

 import requests

 def request_test():
url = 'http://httpbin.org/get'
response = requests.get(url)
print(type(response.text), response.text)
print(type(response.content), response.content) if __name__ == '__main__':
request_test()

直接得到响应体。

 <class 'str'> {"args":{},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Host":"httpbin.org","User-Agent":"python-requests/2.18.4"},"origin":"121.61.132.191","url":"http://httpbin.org/get"}

 <class 'bytes'> b'{"args":{},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Host":"httpbin.org","User-Agent":"python-requests/2.18.4"},"origin":"121.61.132.191","url":"http://httpbin.org/get"}\n

GET方法中传递参数的三种方式:

  • 将字典形式的参数用urllib.parse.urlencode()函数编码成url参数:

     import urllib.parse
    
     if __name__ == '__main__':
    base_url = 'http://httpbin.org/'
    params = {
    'key1': 'value1',
    'key2': 'value2'
    }
    full_url = base_url + urllib.parse.urlencode(params)
    print(full_url)
     http://httpbin.org/key1=value1&key2=value2
  • 直接在urllib.request.get()函数中使用params参数:
     import requests
    
     if __name__ == '__main__':
    payload = {
    'key1': 'value1',
    'key2': 'value2'
    }
    response = requests.get('http://httpbin.org/get', params=payload)
    print(response.url)
     http://httpbin.org/key1=value1&key2=value2
  • url直接包含参数:
     http://httpbin.org/get?key2=value2&key1=value1

2.2 基于requests库的POST请求,并用session保持会话

登陆ChinaUnix论坛,获取首页源码,然后访问一个文章。首先不使用Session看一下什么效果:

 import requests

 def get_page():
6   url = 'http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LcN2z'
  headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
  }
  data = {
11     'username': 'StrivePy',
    'password': 'XXX'
  }
  response = requests.post(url=url, data=data, headers=headers)
  page_source = response.text
  print(response.status_code)
  print(page_source)   url1 = 'http://bbs.chinaunix.net/thread-4263876-1-1.html'
  response1 = requests.get(url=url1, headers=headers)
  page_source1 = response1.text
  print(response1.status_code)
  print(page_source1) if __name__ == '__main__':
  get_page()

结果显示访问其它文章时为游客模式。接下来用session来维持会话看一下效果:

 import requests

 def get_page():
  url = 'http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LcN2z'
  headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
  }
  data = {
    'username': 'StrivePy',
    'password': 'XXX'
  }
  session = requests.session()
  response = session.post(url=url, data=data, headers=headers)
  page_source = response.text
  print(response.status_code)
  print(page_source)   url1 = 'http://bbs.chinaunix.net/thread-4263876-1-1.html'
  response1 = session.get(url=url1, headers=headers)
  page_source1 = response1.text
22   print(response1.status_code)
  print(page_source1) if __name__ == '__main__':
  get_page()

结果显示访问其它文章时,显示为登陆状态,会话保持住了。使用session的效果类似于urllib库临时使用opener或者将opener安装为全局的效果。

2.3 基于requests库使用代理请求

在requests库中使用代理:

 import requests

 def proxy_test():
url = 'http://myip.kkcha.com/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'
}
proxy = {
'https': '61.135.217.7: 80'
}
response = requests.get(url=url, headers=headers, proxies=proxy)
print(response.text) if __name__ == '__main__':
proxy_test()

这个请求到的代码显示IP还是本地的网络IP,代理没起作用,具体原因有待研究。

Python3 urllib库和requests库的更多相关文章

  1. python3好用的requests库

    python3好用的requests库 requests是什么? requests是基于urllib编写的http库,支持python3,比urllib更好用,更简单.之前使用python写一些htt ...

  2. 【Python爬虫】HTTP基础和urllib库、requests库的使用

    引言: 一个网络爬虫的编写主要可以分为三个部分: 1.获取网页 2.提取信息 3.分析信息 本文主要介绍第一部分,如何用Python内置的库urllib和第三方库requests库来完成网页的获取.阅 ...

  3. python库:bs4,BeautifulSoup库、Requests库

    Beautiful Soup https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/ Beautiful Soup 4.2.0 文档 htt ...

  4. [python爬虫]Requests-BeautifulSoup-Re库方案--Requests库介绍

    [根据北京理工大学嵩天老师“Python网络爬虫与信息提取”慕课课程编写  文章中部分图片来自老师PPT 慕课链接:https://www.icourse163.org/learn/BIT-10018 ...

  5. 爬虫请求库之requests库

    一.介绍 介绍:使用requests可以模拟浏览器的请求,比之前的urllib库使用更加方便 注意:requests库发送请求将网页内容下载下来之后,并不会执行js代码,这需要我们自己分析目标站点然后 ...

  6. 请求库之requests库

    目录 一.介绍 二.基于get请求 1 基本请求 2 带参数的get请求 3 请求携带cookie 三.基于post请求 1 基本用法 2 发送post请求,模拟浏览器的登录行为 四.响应Respon ...

  7. requests库和urllib包对比

    python中有多种库可以用来处理http请求,比如python的原生库:urllib包.requests类库.urllib和urllib2是相互独立的模块,python3.0以上把urllib和ur ...

  8. python关于urllib库与requests

    对于这两个库来说个人推荐使用requests库 下面用实例来说明 urllib库: requests库: 实现同样功能: 实现同样的功能下urllib比request步骤更复杂,这个对于我们编程来说是 ...

  9. python3.5 使用tkinter 和requests库实现天气图像化显示

    1 """ 该python小例子考察使用了tkinter库,requests库 其中: requests库用来发送网络请求 thkinter用来显示图形化界面 请求的天气 ...

随机推荐

  1. 生产案例、Linux出现假死,怎么回事?

    1.什么是假死 所谓假死,就是能ping通,但是ssh不上去:任何其他操作也都没反应,包括上面部署的nginx也打不开页面. 2.假死其实很难出现一次 作为一个多任务操作系统,要把系统忙死,忙到ssh ...

  2. create a bootable USB stick on Ubuntu

    https://tutorials.ubuntu.com/tutorial/tutorial-create-a-usb-stick-on-ubuntu?_ga=2.141187314.17572770 ...

  3. linux双网卡绑定实现冗余与负载均衡

    1 编辑/etc/modprobe.conf   在/etc/modprobe.conf里加入如下两行: alias bond0 bonding options bond0 mode=1 miimon ...

  4. 好久没玩laravel了,5.6玩下(三)

    好了,基础的测试通了,咱们开始增删改了 思路整理 先创建项目功能控制器 然后设置路由访问规则 然后开发项目的增删改功能 1 先创建项目的控制器 php artisan make:controller ...

  5. testng报告发邮件后css样式缺失问题

    问题:用reportng把代替testng报告后,邮件中不显示html样式 解决方案:把依赖的文件,加到邮件附件 Jenkins发邮件的时候,把依赖文件作为附件发送. 结果看到样式了:

  6. js脚本代码调试小技巧

    以前写js代码调试代码查看数据是否正确的时候不知道F12(开发者工具),都是alert(xxx)或者console.log(xxx), 现在知道还可以用document.write或者try...ca ...

  7. cobbler全自动批量安装部署linux

    Cobbler的设计方式: Cobbler的配置结构基于一组注册的对象.每个对象表示一个与另一个实体相关联的实体(该对象指向另一个对象,或者另一个对象指向该对象).当一个对象指向另一个对象时,它就继承 ...

  8. 使用通用mapper 生成代码

    参考通用mapper 文档:https://github.com/abel533/Mapper/wiki/4.1.mappergenerator 使用maven 的方法: 1,修改pom.xml &l ...

  9. ComputeSignature 中行支付签名报错(win7 64位系统)

    在做中行加密验签的时候出现的问题.原本在XP系统下可以正常运行的,现在换了win7 64位系统就出现了这个问题,没头绪 所以发上来求各位大大支招 有什么好的解决方案.. 我的解决办法: 1.C:\Do ...

  10. Ansible 书写我的playbook

    mysql 创建数据库 - hosts: localhost  remote_user: root  tasks: - name: test mysql    mysql_db:      name: ...