Python使用requests来抓取网页

简介: 文章转载自:http://www.yangyanxing.com/?p=10791. requests介绍  早就听说requests的库的强大,只是还没有接触,今天接触了一下,发现以前使用urllib,urllib2等方法真是太搓了……  ...


文章转载自:http://www.yangyanxing.com/?p=1079


1. requests介绍

  早就听说requests的库的强大,只是还没有接触,今天接触了一下,发现以前使用urllib,urllib2等方法真是太搓了……
  这里写些简单的使用初步作为一个记录

一、安装python的requests模块,使用pip或easy_install都可以


二、发送无参数的get请求

r = requests.get('http://httpbin.org/get')
print r.text
{
  "args": {},
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "close",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.3.0 CPython/2.6.6 Windows/7",
    "X-Request-Id": "8a28bbea-55cd-460b-bda3-f3427d66b700"
  },
  "origin": "124.192.129.84",
  "url": "http://httpbin.org/get"
}

三、发送带参数的get请求,将key与value放入一个字典中,通过params参数来传递,其作用相当于urllib.urlencode

import requests
pqyload = {'q':'杨彦星'}
r = requests.get('http://www.so.com/s',params = pqyload)
r.url
u'http://www.so.com/s?q=%E6%9D%A8%E5%BD%A6%E6%98%9F'

四、发送post请求,通过data参数来传递,

payload = {'a':'杨','b':'hello'}
r = requests.post("http://httpbin.org/post", data=payload)
print r.text
{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "a": "u6768",
    "b": "hello"
  },
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "close",
    "Content-Length": "19",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.3.0 CPython/2.6.6 Windows/7",
    "X-Request-Id": "c81cb937-04b8-4a2d-ba32-04b5c0b3ba98"
  },
  "json": null,
  "origin": "124.192.129.84",
  "url": "http://httpbin.org/post"
}

可以看到,post参数已经传到了form里,data不光可以接受字典类型的数据,还可以接受json等格式

payload = {'a':'杨','b':'hello'}
import json
r = requests.post('http://httpbin.org/post', data=json.dumps(payload))

五、发送文件的post类型,这个相当于向网站上传一张图片,文档等操作,这时要使用files参数

url = 'http://httpbin.org/post'
files = {'file': open('touxiang.png', 'rb')}
r = requests.post(url, files=files)
5.1 定制headers,使用headers参数来传递
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)

六、响应内容

6.1 响应状态码
r = requests.get('http://httpbin.org/get')
print r.status_code
6.2 响应头
print r.headers
{'content-length': '519', 'server': 'gunicorn/18.0', 'connection': 'keep-alive', 'date': 'Sun, 15 Jun 2014 14:19:52 GMT', 'access-control-allow-origin': '*', 'content-type': 'application/json'}
也可以取到这个个别的响应头用来做一些判断,这里的参数是不区分大小写的
r.headers[‘Content-Type’]
r.headers.get(‘Content-Type’)
6.3 响应内容,前面已经在应用了
r.text
r.content

七、获取响应中的cookies

r = requests.get('http://www.baidu.com')
r.cookies['BAIDUID']
'D5810267346AEFB0F25CB0D6D0E043E6:FG=1'
也可以自已定义请求的COOKIES
url = 'http://httpbin.org/cookies'
cookies = {'cookies_are':'working'}
r = requests.get(url,cookies = cookies)
print r.text
{
  "cookies": {
       "cookies_are": "working"
  }
}
cookies还有很多,因为目前我也还不是很多,以后再扩充吧

八、使用timeout参数设置超时时间

requests.get('http://github.com', timeout=1)
<Response [200]>
如果将时间设置成非常小的数,如requests.get('http://github.com', timeout=0.001),那么如果在timeout的时间内没有连接,那么将会抛出一个Timeout的异常

九、访问中使用session

先初始化一个session对象,s = requests.Session()
然后使用这个session对象来进行访问,r = s.post(url,data = user)
参考文章 http://blog.csdn.net/iloveyin/article/details/21444613 基本上都是从这扒的代码


2. 爬虫实例

  以下通过访问人人网来获取首页中的最近来访问,然后再访问查看更多的来访来读取更多的最近来访
更多的来访就是以带session的访问http://www.renren.com/myfoot.do

#coding:utf-8
import requests
import re

url = r'http://www.renren.com/ajaxLogin'

user = {'email':'email','password':'pass'}
s = requests.Session()
r = s.post(url,data = user)

html = r.text
visit = []
first = re.compile(r'</span><span class="time-tip first-tip"><span class="tip-content">(.*?)</span>')
second = re.compile(r'</span><span class="time-tip"><span class="tip-content">(.*?)</span>')
third = re.compile(r'</span><span class="time-tip last-second-tip"><span class="tip-content">(.*?)</span>')
last = re.compile(r'</span><span class="time-tip last-tip"><span class="tip-content">(.*?)</span>')
visit.extend(first.findall(html))
visit.extend(second.findall(html))
visit.extend(third.findall(html))
visit.extend(last.findall(html))
for i in visit:
    print i

print '以下是更多的最近来访'
vm = s.get('http://www.renren.com/myfoot.do')
fm = re.compile(r'"name":"(.*?)"')
visitmore = fm.findall(vm.text)
for i in visitmore:
    print i

renren


目录
相关文章
|
7天前
|
人工智能 Python
【Python实用技能】建议收藏:自动化实现网页内容转PDF并保存的方法探索(含代码,亲测可用)
【Python实用技能】建议收藏:自动化实现网页内容转PDF并保存的方法探索(含代码,亲测可用)
26 0
|
8天前
|
数据采集 存储 JSON
Python爬虫面试:requests、BeautifulSoup与Scrapy详解
【4月更文挑战第19天】本文聚焦于Python爬虫面试中的核心库——requests、BeautifulSoup和Scrapy。讲解了它们的常见问题、易错点及应对策略。对于requests,强调了异常处理、代理设置和请求重试;BeautifulSoup部分提到选择器使用、动态内容处理和解析效率优化;而Scrapy则关注项目架构、数据存储和分布式爬虫。通过实例代码,帮助读者深化理解并提升面试表现。
15 0
|
10天前
|
Python
使用Python的Requests库进行网络请求和抓取网页数据
【4月更文挑战第20天】使用Python Requests库进行网络请求和网页数据抓取的步骤包括:安装库(`pip install requests`)、导入库、发送GET/POST请求、检查响应状态码、解析内容、处理Cookies、设置请求头以及异常处理。通过`response`对象访问响应信息,如`status_code`、`text`、`content`和`cookies`。可设置`headers`模拟用户代理,用`try-except`处理异常。
19 7
|
10天前
|
数据挖掘 API 数据安全/隐私保护
python请求模块requests如何添加代理ip
python请求模块requests如何添加代理ip
|
11天前
|
Python
如何使用Python的Requests库进行网络请求和抓取网页数据?
【4月更文挑战第19天】使用Python Requests库进行网络请求和网页数据抓取:安装库,导入requests,发送GET/POST请求,检查状态码(如`status_code==200`表示成功),解析响应内容(如`response.text`),处理Cookies和请求头,以及用try-except捕获异常。更多功能可深入学习Requests库。
10 2
|
18天前
|
开发者 索引 Python
实践:如何使用python在网页的表格里抓取信息
实践:如何使用python在网页的表格里抓取信息
|
Python Windows
Python 3 抓取网页资源的 N 种方法
1、最简单 import urllib.requestresponse = urllib.request.urlopen('http://python.org/')html = response.
737 0
|
Python Windows
python3 抓取网页资源的 N 种方法
1、最简单 import urllib.requestresponse = urllib.request.urlopen('http://python.org/')html = response.
1126 0
|
1天前
|
网络协议 算法 网络架构
Python网络编程之udp编程、黏包以及解决方案、tcpserver
Python网络编程之udp编程、黏包以及解决方案、tcpserver
|
1天前
|
机器学习/深度学习 数据挖掘 算法框架/工具
Python:编程的艺术与魅力
Python:编程的艺术与魅力
10 3