6、web爬虫讲解2—urllib库爬虫—基础使用—超时设置—自动模拟http请求

简介: 利用python系统自带的urllib库写简单爬虫 urlopen()获取一个URL的html源码read()读出html源码内容decode("utf-8")将字节转化成字符串 #!/...

利用python系统自带的urllib库写简单爬虫

urlopen()获取一个URL的html源码
read()读出html源码内容
decode("utf-8")将字节转化成字符串

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib.request
html = urllib.request.urlopen('http://edu.51cto.com/course/8360.html').read().decode("utf-8")
print(html)
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-param" content="_csrf">
    <meta name="csrf-token" content="X1pZZnpKWnQAIGkLFisPFT4jLlJNIWMHHWM6HBBnbiwPbz4/LH1pWQ==">

正则获取页面指定内容

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib.request
import re
html = urllib.request.urlopen('http://edu.51cto.com/course/8360.html').read().decode("utf-8")   #获取html源码
pat = "51CTO学院Python实战群\((\d*?)\)"      #正则规则,获取到QQ号
rst = re.compile(pat).findall(html)
print(rst)

#['325935753']

urlretrieve()将网络文件下载保存到本地,参数1网络文件URL,参数2保存路径

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from urllib import request
import re
import os

file_path = os.path.join(os.getcwd() + '/222.html')    #拼接文件保存路径
# print(file_path)
request.urlretrieve('http://edu.51cto.com/course/8360.html', file_path) #下载这个文件保存到指定路径

urlcleanup()清除爬虫产生的内存

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from urllib import request
import re
import os

file_path = os.path.join(os.getcwd() + '/222.html')    #拼接文件保存路径
# print(file_path)
request.urlretrieve('http://edu.51cto.com/course/8360.html', file_path) #下载这个文件保存到指定路径
request.urlcleanup()

info()查看抓取页面的简介

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib.request
import re
html = urllib.request.urlopen('http://edu.51cto.com/course/8360.html')   #获取html源码
a = html.info()
print(a)

# C:\Users\admin\AppData\Local\Programs\Python\Python35\python.exe H:/py/15/chshi.py
# Date: Tue, 25 Jul 2017 16:08:17 GMT
# Content-Type: text/html; charset=UTF-8
# Transfer-Encoding: chunked
# Connection: close
# Set-Cookie: aliyungf_tc=AQAAALB8CzAikwwA9aReq63oa31pNIez; Path=/; HttpOnly
# Server: Tengine
# Vary: Accept-Encoding
# Vary: Accept-Encoding
# Vary: Accept-Encoding

getcode()获取状态码

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib.request
import re
html = urllib.request.urlopen('http://edu.51cto.com/course/8360.html')   #获取html源码
a = html.getcode()  #获取状态码
print(a)

#200

geturl()获取当前抓取页面的URL

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib.request
import re
html = urllib.request.urlopen('http://edu.51cto.com/course/8360.html')   #获取html源码
a = html.geturl()  #获取当前抓取页面的URL
print(a)

#http://edu.51cto.com/course/8360.html

timeout抓取超时设置,单位为秒

是指抓取一个页面时对方服务器响应太慢,或者很久没响应,设置一个超时时间,超过超时时间就不抓取了

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import urllib.request
import re
html = urllib.request.urlopen('http://edu.51cto.com/course/8360.html',timeout=30)   #获取html源码
a = html.geturl()  #获取当前抓取页面的URL
print(a)

#http://edu.51cto.com/course/8360.html

自动模拟http请求

http请求一般常用的就是get请求和post请求

get请求

比如360搜索,就是通过get请求并且将用户的搜索关键词传入到服务器获取数据的

所以我们可以模拟百度http请求,构造关键词自动请求

quote()将关键词转码成浏览器认识的字符,默认网站不能是中文

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib.request
import re
gjc = "手机"     #设置关键词
gjc = urllib.request.quote(gjc)         #将关键词转码成浏览器认识的字符,默认网站不能是中文
url = "https://www.so.com/s?q="+gjc     #构造url地址
# print(url)
html = urllib.request.urlopen(url).read().decode("utf-8")  #获取html源码
pat = "(\w*<em>\w*</em>\w*)"            #正则获取相关标题
rst = re.compile(pat).findall(html)
# print(rst)
for i in rst:
    print(i)                            #循环出获取的标题

    # 官网 < em > 手机 < / em >
    # 官网 < em > 手机 < / em >
    # 官网 < em > 手机 < / em > 这么低的价格
    # 大牌 < em > 手机 < / em > 低价抢
    # < em > 手机 < / em >
    # 淘宝网推荐 < em > 手机 < / em >
    # < em > 手机 < / em >
    # < em > 手机 < / em >
    # < em > 手机 < / em >
    # < em > 手机 < / em >
    # 苏宁易购买 < em > 手机 < / em >
    # 买 < em > 手机 < / em >
    # 买 < em > 手机 < / em >

post请求

urlencode()封装post请求提交的表单数据,参数是字典形式的键值对表单数据
Request()提交post请求,参数1是url地址,参数2是封装的表单数据

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib.request
import urllib.parse

posturl = "http://www.iqianyue.com/mypost/"
shuju = urllib.parse.urlencode({                #urlencode()封装post请求提交的表单数据,参数是字典形式的键值对表单数据
    'name': '123',
    'pass': '456'
    }).encode('utf-8')
req = urllib.request.Request(posturl,shuju)     #Request()提交post请求,参数1是url地址,参数2是封装的表单数据
html = urllib.request.urlopen(req).read().decode("utf-8")  #获取post请求返回的页面
print(html)

【转载自:http://www.lqkweb.com

相关文章
|
前端开发 JavaScript 安全
前端性能调优:HTTP/2与HTTPS在Web加速中的应用
【10月更文挑战第27天】本文介绍了HTTP/2和HTTPS在前端性能调优中的应用。通过多路复用、服务器推送和头部压缩等特性,HTTP/2显著提升了Web性能。同时,HTTPS确保了数据传输的安全性。文章提供了示例代码,展示了如何使用Node.js创建一个HTTP/2服务器。
404 3
|
10月前
|
中间件 Go
Golang | Gin:net/http与Gin启动web服务的简单比较
总的来说,`net/http`和 `Gin`都是优秀的库,它们各有优缺点。你应该根据你的需求和经验来选择最适合你的工具。希望这个比较可以帮助你做出决策。
528 35
|
7月前
|
数据采集 Web App开发 iOS开发
解决Python爬虫访问HTTPS资源时Cookie超时问题
解决Python爬虫访问HTTPS资源时Cookie超时问题
|
缓存 网络协议 前端开发
Web 性能优化|了解 HTTP 协议后才能理解的预加载
本文旨在探讨和分享多种预加载技术及其在提升网站性能、优化用户体验方面的应用。
Web 性能优化|了解 HTTP 协议后才能理解的预加载
|
域名解析 缓存 网络协议
Web基础与HTTP协议
通过掌握这些基础知识和技术,开发者可以更加高效地构建和优化Web应用,提供更好的用户体验和系统性能。
336 15
|
缓存 安全 网络安全
HTTP/2与HTTPS在Web加速中的应用
HTTP/2与HTTPS在Web加速中的应用
566 11
|
前端开发 安全 应用服务中间件
前端性能调优:HTTP/2与HTTPS在Web加速中的应用
【10月更文挑战第26天】随着互联网的快速发展,前端性能调优成为开发者的重要任务。本文探讨了HTTP/2与HTTPS在前端性能优化中的应用,介绍了二进制分帧、多路复用和服务器推送等特性,并通过Nginx配置示例展示了如何启用HTTP/2和HTTPS,以提升Web应用的性能和安全性。
356 3
|
10月前
|
数据采集 测试技术 C++
无headers爬虫 vs 带headers爬虫:Python性能对比
无headers爬虫 vs 带headers爬虫:Python性能对比
|
数据采集 存储 JSON
Python网络爬虫:Scrapy框架的实战应用与技巧分享
【10月更文挑战第27天】本文介绍了Python网络爬虫Scrapy框架的实战应用与技巧。首先讲解了如何创建Scrapy项目、定义爬虫、处理JSON响应、设置User-Agent和代理,以及存储爬取的数据。通过具体示例,帮助读者掌握Scrapy的核心功能和使用方法,提升数据采集效率。
620 6
|
10月前
|
数据采集 存储 监控
Python 原生爬虫教程:网络爬虫的基本概念和认知
网络爬虫是一种自动抓取互联网信息的程序,广泛应用于搜索引擎、数据采集、新闻聚合和价格监控等领域。其工作流程包括 URL 调度、HTTP 请求、页面下载、解析、数据存储及新 URL 发现。Python 因其丰富的库(如 requests、BeautifulSoup、Scrapy)和简洁语法成为爬虫开发的首选语言。然而,在使用爬虫时需注意法律与道德问题,例如遵守 robots.txt 规则、控制请求频率以及合法使用数据,以确保爬虫技术健康有序发展。
1419 31