【python爬虫自学记录】【7】-urllib基础,超时设置,自动模拟HTTP请求get请求实战和post请求实战

urllib基础

urlretrieve(网站,本地存储地址)

直接下载网页到本地

import urllib.request

urllib.request.urlretrieve("http://www.baidu.com","D:\\pycharmprojects\\untitled\\dld.html")

urlcleanup()清除缓存

import urllib.request

urllib.request.urlcleanup()

urlinfo()查看网页相应简介信息

file = urllib.request.urlopen("https://www.csdn.net/")
print(file.info())

getcode()

返回网页爬取的状态码,可以检测是否是死链,只有200是正常状态

file = urllib.request.urlopen("https://www.csdn.net/")
print(file.getcode())

geturl()

获取当前访问网页的url
自动爬虫的时候方便查看进行到哪个页面了

file = urllib.request.urlopen("https://www.csdn.net/")
print(file.geturl())

超时设置

由于网络速度,或者服务器问题都需要时间。如果网页长时间未响应,则判断这个网页超时。
所以有时候我们需要根据自己的需求设置一个超时的时间值

for i in range(0,100):
    file = urllib.request.urlopen("http://www.baidu.com",timeout=1)
    try:
        print(len(file.read()))
    except Exception as err:
        print("当前异常",err)

自动模拟HTTP请求

请求方式有很多种,这里说post,get两种,比如登录,搜索会用到

get实现百度自动搜索

keywd = "python"
url = "http://www.baidu.com/s?wd="+keywd
urlopen=urllib.request.urlopen(url)
print(urlopen.geturl())
data = urlopen.read().decode("utf-8")
pat = "data-tools='{\"title\":\"(.*?)\","
rst = re.compile(pat).findall(data)
print(rst)

输出
[‘python官方网站 - Welcome to Python.org’, ‘Python VS C#,哪个更适合建筑业的人?_腾讯新闻’, ‘python官网 - Download Python | Python.org’, ‘Python 基础教程 | 菜鸟教程’, ‘Python-薯条编程-在线教程-小班授课高薪就业培训’, ‘一颗韭菜的自我修养:用Python分析下股市,练练手|Python_新浪科技_新…’, ‘你都用 Python 来做什么? - 知乎’, ‘Python基础教程,Python入门教程(非常详细)_C语言中文网’]

ps…多次搜索就会发现搜不出来,然后使用geturl发现进入了图形认证页面,就是被反爬了。所以可以运行的时候不断换一下搜索关键词

如果输入的是keyword是中文,则需要转码
keywd = "在逃扇贝"
keywd = urllib.request.quote(keywd)  #转码
url = "http://www.baidu.com/s?wd="+keywd
urlopen=urllib.request.urlopen(url)
print(urlopen.geturl())
data = urlopen.read().decode("utf-8")
pat = "data-tools='{\"title\":\"(.*?)\","
rst = re.compile(pat).findall(data)
print(rst)
按照页码来逐页提取关键词
keywd = "扇贝"
keywd = urllib.request.quote(keywd)  #转码

#page = (num-1)*10
for i in range(1,11):
    url = "http://www.baidu.com/s?wd="+keywd+"&pn="+str((i-1)*10)
    urlopen=urllib.request.urlopen(url)

    print(urlopen.geturl())

    data = urlopen.read().decode("utf-8")
    pat = "data-tools='{\"title\":\"(.*?)\","
    rst = re.compile(pat).findall(data)
    for j in range(0,len(rst)):
        print(rst[j])

post请求

运用在输入名字密码的框里面
以下示例是传入一个name和pass到简单网站进行登录

url = "https://www.iqianyue.com/mypost"
data = urllib.parse.urlencode({
     
    "name":"zz123",
    "pass":"123",
}).encode("utf-8")
#进行post,就需要使用urllib.request下面的Request(真实post地址,post数据)
req = urllib.request.Request(url,data)
rst = urllib.request.urlopen(req).read().decode("utf-8")
print(rst)
fh = open("D:\\pycharmprojects\\untitled\\post.html","w")
fh.write(rst)
fh.close()
urllib.request.urlcleanup()

你可能感兴趣的:(python爬虫自学,python,http)