第三百二十七节,web爬虫讲解2—urllib库爬虫—基础使用—超时设置—自动模拟http请求...

news/2024/7/19 12:06:03 标签: 爬虫, python


第三百二十七节,web爬虫讲解2—urllib库爬虫

 

利用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 lang="zh-CN">
<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.niftyadmin.cn/n/979379.html

相关文章

PAT乙级 1056 组合数的和 (15 分)

PAT乙级 1056 组合数的和 (15 分) 给定 N 个非 0 的个位数字&#xff0c;用其中任意 2 个数字都可以组合成 1 个 2 位的数字。要求所有可能组合出来的 2 位数字的和。例如给定 2、5、8&#xff0c;则可以组合出&#xff1a;25、28、52、58、82、85&#xff0c;它们的和为330。…

MVC总结--MVC简单介绍以及和WebForm差别

什么是MVCMVC&#xff08;Model-View-Controller。模型—视图—控制器模式&#xff09;用于表示一种软件架构模式。它把软件系统分为三个基本部分&#xff1a;模型&#xff08;Model&#xff09;&#xff0c;视图&#xff08;View&#xff09;和控制器&#xff08;Controller&a…

剑指offer——扑克牌顺子

题目描述 LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张_)…他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿&#xff01;&#xff01;“红心A,黑桃3,小王,大王,方片5”,“Oh My…

使用Codeblock搭建Windows下Objec-c学习环境

学习Object-c如果使用的是Windows&#xff0c;一般推荐使用虚拟机&#xff0c;但是太重量级了&#xff0c;先要下载OS-X&#xff0c;又要下载x-code。这里推荐一种比较简便的方式&#xff0c;使用code-block来搭建简易的Object-c学习环境&#xff0c;下载地址是&#xff1a;htt…

剑指offer——孩子们的游戏(圆圈中最后剩下的数)

题目描述 每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列…

05-黑马程序员------C 语言学习笔记---C语言中的宏定义

黑马程序员------<a href"http://www.itheima.com" target"blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流&#xff01; ------- 1.5 C语言程序的运行过程 01 源程序&#xff1a;由高级语言或汇编语言编写&#xff0c…

报错fp = builtins.open(filename, “rb“)解决

fp builtins.open(filename, "rb")报错 原因&#xff1a; 地址的 \ 被当成转义字符处理 导致地址错误 解决方案&#xff1a; 1 在地址前面加r 防止转义 2 把所有的单反斜杠变成双反斜杠

字节跳动——特征提取

[编程题]特征提取 时间限制&#xff1a;C/C 1秒&#xff0c;其他语言2秒 空间限制&#xff1a;C/C 32M&#xff0c;其他语言64M 小明是一名算法工程师&#xff0c;同时也是一名铲屎官。某天&#xff0c;他突发奇想&#xff0c;想从猫咪的视频里挖掘一些猫咪的运动信息。为了提…