[python] python中的urllib模块

本文介绍如何使用Python的urllib库来抓取网页内容,并展示了如何模拟浏览器行为进行请求,包括设置请求头信息、处理URL编码等关键技术点。

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

1.发送请求获取html页面

import urllib.request

response = urllib.request.urlopen("http://www.baidu.com/")

html = response.read().decode('utf-8')

print(html)

2.模拟浏览器发送请求获取html页面

指定请求头的方式

import urllib.request

url = "http://www.baidu.com/"

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"
}
request = urllib.request.Request(url=url, headers=headers)

response = urllib.request.urlopen(request) #response是类文件对象

html = response.read().decode('utf-8')

添加请求头的方式

import urllib.request

url = "http://www.baidu.com/"
key = "User-Agent"
value = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"

request = urllib.request.Request(url=url)
request.add_header(key,value)
# request.get_header("User-agent,user_agent)

response = urllib.request.urlopen(request) #response是类文件对象

html = response.read().decode('utf-8')

3.打印响应相关信息

# response.getcode()  获取响应码
# response.geturl() 返回实际数据的url,防止重定向
# response.info() 响应报头信息

4.url中的中文编码问题

import urllib.parse

wd={"wd" : "阿里巴巴"}
encodedWd = urllib.parse.urlencode(wd)
# urllib.unquote(encodedWd)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值