Python学习总结(四)——网络爬虫urllib库函数

本文介绍使用Python进行网络爬虫的基本方法,包括利用urllib库发送GET请求获取网页内容,使用正则表达式解析图片链接,并将图片下载到本地。同时介绍了urllib库中各个模块的功能及其常见用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#coding=utf-8
'''import urllib
b=urllib.urlopen('http://www.baidu.com')
b.read()'''
'''
Urllib是python内置的HTTP请求库
包括以下模块
urllib.request            请求模块
urllib.error              异常处理模块
urllib.parse              url解析模块
urllib.robotparser        robots.txt解析模块
'''
#urllib request
#get请求方式

import urllib.request
import re#正则表达式

#response = urllib.request.urlopen('http://www.12306.com')
'''urlopen一般常用的有三个参数,它的参数如下:
   urllib.requeset.urlopen(url,data,timeout)
   response.read()可以获取到网页的内容,如果没有read(),将返回如下内容
   response.info()远程服务器头信息
   response.getcode() 返回为200找到服务器,返回404没有找到  5开头,服务器bug
   urllib.request.urlretrieve(address,filename) 从网络下载网页内容到本地
 '''
#print(response)
#print(response.read().decode('utf-8'))
#print(response.info())#远程服务器头信息
#print(response.getcode())#返回为200找到服务器,返回404没有找到  5开头,服务器bug
#re=urllib.request.urlretrieve("https://img-blog.youkuaiyun.com/20180104135540208?watermark/2/text")
#print(re)
#data请求方'
res=urllib.request.urlopen('http://www.douyu.com')
str=res.read().decode('utf-8')
imgList=re.findall(r'src="(.*?\.jpg)"',str)
print(imgList[0])
url=imgList[0]
urllib.request.urlretrieve(url,'C:\\Users\\Administrator\\Desktop\\1.jpg')




'''import urllib.parse
import urllib.request

data = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf8')
print(data)
response = urllib.request.urlopen('http://httpbin.org/post', data=data)
print(response.read())'''

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值