Python3 urllib.request与requests模块请求网页代码

本文介绍使用Python通过两种方式(urllib.request 和 requests)来抓取网页数据的方法,并展示了如何解析并打印出天气信息。

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

爬虫的起点,获取网页代码

#!/usr/bin/env python3
# -*- encoding:utf-8 -*-

# 请求网页代码

import urllib.request

req = urllib.request.Request('http://www.weather.com.cn/adat/sk/101280101.html')

r = urllib.request.urlopen(req)

result = str(r.read(), encoding='utf-8')

print(result, type(result))


#############################

# requests是第三方模块,与上面urllib.request一样的效果。而且跟方便简洁

import requests

res = requests.get("http://www.weather.com.cn/adat/sk/101280101.html")

res.encoding = 'utf-8'

r = res.text

print(type(r), r)

#<class 'str'> {"weatherinfo":{"city":"广州","cityid":"101280101","temp":"24","WD":"东南风","WS":"3级","SD":"80%","WSE":"3","time":"10:25","isRadar":"1","Radar":"JC_RADAR_AZ9200_JB","njd":"暂无实况","qy":"1001"}}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值