鱼C论坛

 找回密码
 立即注册
查看: 1456|回复: 0

[技术交流] Python网络爬虫连载之一

[复制链接]
发表于 2018-1-18 09:52:50 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 payton24 于 2018-1-18 09:56 编辑

最近开始主要看网络爬虫的书,有时顺利,有时还碰到挺多障碍的。
也是时候总结一下怎么做了。

相对于urllib模块,感觉requests模块使用起来更加便利,也容易安装,pip install requests就搞定了。

1. 最简单的例子:
  1. import requests
  2. r = requests.get("http://www.baidu.com")

  3. print(r.encoding)           #文本编码
  4. print(r.status_code)       #响应状态
  5. print(r.text)                  #返回str类型的响应内容,根据响应头部的字符编码进行解码。
  6. print(r.content)             #返回bytes类型的响应内容,会自动解码gzip和deflate编码。
复制代码


2. 定制requests
可以用http://www.httpbin.org/进行测试,方便快捷。

①定制请求头,一般加上User-Agent,还可以添加Host等部分。
  1. import requests
  2. hds={"User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"}
  3. r = requests.get("http://www.httpbin.org/user-agent")
  4. r1 = requests.get("http://www.httpbin.org/user-agent",headers=hds)
  5. print(r.text)
  6. print(r1.text)
复制代码


②定制超时
  1. r2 = requests.get("http://www.httpbin.org/user-agent",headers=hds,timeout=15)
  2. print(r2.text)
复制代码


③传递URL信息,用于在URL中加入特定数据,构建新的URL。
  1. key_dict={'wd':'python'}
  2. r3 = requests.get("http://www.httpbin.org/get",params=key_dict)
  3. r4 = requests.get("http://www.baidu.com/s",params=key_dict)
  4. print(r3.text)
  5. print(r4.text)
复制代码


④发送Post请求
  1. key_dict={'Pw':'python'}
  2. r5 = requests.post("http://www.httpbin.org/post",data=key_dict)
  3. print(r5.text)
复制代码


3.最后附上requests的get、post方法说明。
requests.get方法
  1. Help on function get in module requests.api:

  2. get(url, params=None, **kwargs)
  3.     Sends a GET request.
  4.    
  5.     :param url: URL for the new :class:`Request` object.
  6.     :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
  7.     :param \*\*kwargs: Optional arguments that ``request`` takes.
  8.     :return: :class:`Response <Response>` object
  9.     :rtype: requests.Response
复制代码


requests.post方法
  1. Help on function post in module requests.api:

  2. post(url, data=None, json=None, **kwargs)
  3.     Sends a POST request.
  4.    
  5.     :param url: URL for the new :class:`Request` object.
  6.     :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
  7.     :param json: (optional) json data to send in the body of the :class:`Request`.
  8.     :param \*\*kwargs: Optional arguments that ``request`` takes.
  9.     :return: :class:`Response <Response>` object
  10.     :rtype: requests.Response
复制代码








本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-20 02:53

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表