Python 爬虫系列(二)基本库的使用

本贴最后更新于 395 天前,其中的信息可能已经渤澥桑田

urllib 的使用

urlib 是 python 内置的请求库,不需要额外安装

urllib 包含如下 4 个模块:

  • request:最基本的 http 请求模块,模拟请求发送
  • error:异常处理模块
  • parse:工具模块
  • robotparser:用来识别网站的 robots.txt,用的很少

urlopen 发送请求

使用 urlopen 来发送请求

一个小例子:

import urllib.request

response = urllib.request.urlopen('https://www.python.org')
print(response.read().decode('utf-8'))

response 是一个 HTTPRequest 对象,主要包含 read、readinto、getheader、getheaders、fileno 等方法,以及 msg、version、status、reason、debuglevel、closed 等属性。

urlopen 的 API:

urllib.request.urlopen(url, data=None,[timeout,]*,cafile=None,capath=None,cadeFault=False,context=None)

用法就不写了,写几个小例子吧:

import urllib.request
import urllib.parse

# data参数需要变成字节码
data = bytes(urllib.parse.urlencode({'nanme': 'zhangsan'}), encoding='utf-8')
response = urllib.request.urlopen('https://www.httpbin.org/post', data = data)
print(response.read().decode('utf-8'))

# timeout
response = urllib.request.urlopen('https://www.httpbin.org/get', timeout=0.1)
print(response.read())

Request 发送请求

复杂请求,urlopen 无法满足,比如需要附加 Headers,这时候需要可以用更强大的 Request

# Request的基本使用
request = urllib.request.Request('https://www.python.org')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))

# Request多参数
url = 'https://www.httpbin.org/post'
headers = {
    'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
    'Host': 'www.httpbin.org'
}
dict = {'name': 'zhangsan'}
data = bytes(urllib.parse.urlencode(dict), encoding='utf-8')
req = urllib.request.Request(url=url, data=data, headers=headers, method='POST')
response = urllib.request.urlopen(req)
print(response.read().decode('utf-8'))
  • Python

    Python 是一种面向对象、直译式电脑编程语言,具有近二十年的发展历史,成熟且稳定。它包含了一组完善而且容易理解的标准库,能够轻松完成很多常见的任务。它的语法简捷和清晰,尽量使用无异义的英语单词,与其它大多数程序设计语言使用大括号不一样,它使用缩进来定义语句块。

    535 引用 • 672 回帖
  • 爬虫

    网络爬虫(Spider、Crawler),是一种按照一定的规则,自动地抓取万维网信息的程序。

    106 引用 • 275 回帖 • 1 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...