栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

爬虫爬取百度文库_道客巴巴爬虫?

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

爬虫爬取百度文库_道客巴巴爬虫?

urllib.request模块

Python官网:该模块定义了有助于在复杂世界中打开 URL(主要是 HTTP)的函数和类——基本和摘要身份验证、重定向、cookie 等等

我们可以用python自带的urllib库中的request模块来完成简单的爬取单个网页

    通过模拟浏览器构建一个基本Get请求来爬取
 import urllib.request

 url = 'https://httpbin.org/post'
 reponse = urllib.request.urlopen(url)
 #用urlopen方法打开url
 #response 是 HTTPResposne 类型的对象
 print( response.read().decode('utf-8') )
 #以utf-8编码方式解码读取返回网页的内容,并打印出来

https://httpbin.org 网站可以提供 HTTP 请求测试

    通过模拟浏览器构建一个基本Post请求来爬取
 import urllib.request,parse

 url = 'https://httpbin.org/Post'
 dict = {'name':'liu'}

 str = urllib.parse.urlencode(dic)
 # 将字典dict序列化为 GET 请求参数并返回
 #GET请求参数就是URL ?后面的 赋值语句
 例如:checkout = 1 & Id=1
 
 data = bytes(str,encoding='utf-8')
 # 按照encoding的值来将str转码成字节流对象并返回

try:
     reponse = urllib.request.urlopen(url,data = data,timeout = 2)
     # 传递data给data参数(必须是bytes类型)并设置超时时间为2秒
     # 超过2秒抛出 TimeoutError 异常
     #一旦传递了data参数,这变成了一个Post请求
     
     print( response.read().decode('utf-8') )
     
except urllib.error.URLError as e:
  if isinstance(e.reason, socket.timeout):
      print('TIME OUT')
    利用Request类灵活构建请求来爬取
import urllib.request

url = 'https://httpbin.org/post'

#请求头
headers = {
 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
 'Host': 'httpbin.org'
}

dict = {'name':'liu'}
str = urllib.parse.urlencode(dic)
data = bytes(str,encoding='utf-8')

#用url,data(必须是bytes类型),headers,POST实参构造Request对象
request = urllib.request.Request(url,data=data, headers=headers, method='POST')

response = urllib.request.urlopen(request)
#这里urlopen参数要么是url,要么是Request类型对象

 print( response.read().decode('utf-8') )
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/783264.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号