python爬虫urllib库使用

urllib包括以下四个模块:

  1.request:基本的HTTP请求模块,可以用来模拟发送请求。就像在浏览器里输入网址然后回车一样,只需要给库方法传入URL以及额外的参数,就可以模拟实现这个过程。

  2.error:异常处理模块

  3.parse:提供了许多URL处理方法,如拆分、解析、合并等

  4.robotparser:主要用来识别网站的robots.txt文件,判断哪些网站可以爬(很少用)

1.1发送请求

  1urlopen()

import urllib.request
response = urllib.request.urlopen('https://baike.baidu.com/item/csdn/172150?fr=aladdin')
print(response.read().decode('UTF-8')) #read()返回网页内容

结果:

#查看返回类型
import
urllib.request response = urllib.request.urlopen('https://baike.baidu.com/item/csdn/172150?fr=aladdin') print(type(response))

status属性

import urllib.request
response = urllib.request.urlopen('https://baike.baidu.com/item/csdn/172150?fr=aladdin')
print(response.status)
print(response.getheaders())
print(response.getheader('Server'))

猜你喜欢

转载自www.cnblogs.com/alex-xxc/p/9914831.html