Python爬虫速成之路(2):爬天气情况

 hello hello~ ,这里是绝命Coding——老白~💖💖 ,欢迎大家点赞🥳🥳关注💥💥收藏🌹🌹🌹
19d95742d45b4220ad0ae0359ffcba93.png

💥个人主页绝命Coding-CSDN博客
💥 所属专栏后端技术分享
这里将会不定期更新有关后端、前端的内容,希望大家多多点赞关注收藏💖

 历史文章:

Python爬虫速成之路(1):获取网页源代码-CSDN博客

 

使用requests.get()方法发送HTTP请求,并通过content属性获取网页的源代码

正则表达式(.*?):它可以匹配任意长度的字符串,比如abcde,正则表达式a(.*?)e,它就会匹配上bcd。(基本后续的爬虫这一个正则表达式就已经够用了,万能)

import urllib.request as http
import re

#【天气预报】天气预报7天,10天,15天_全国天气网
url = 'http://tianqi.so.com/weather/101281901'
#获取网页源代码
content = http.urlopen(url).read().decode("utf-8")
#.*? 后面多个问号,代表非贪婪模式,也就是说只匹配符合条件的最少字符
pattern = re.findall(r'<div class="temperature">(.*?)</div>',content)
#<div class="temperature">13</div>
print('今天的温度是:{}°'.format(pattern[0]))

优化:

import requests  
import re  
content = requests.get("http://tianqi.so.com/weather/101281901").content.decode()  #获取网页源代码
pattern = re.findall(r'<div class="temperature">(.*?)</div>',content)  
print("今天的温度是:{}°".format(pattern[0]))

这里re.findall里面要求传入的是str类型
从str到bytes:调用方法encode().
从bytes到str:调用方法decode()

 

 更多精彩内容请关注:绝命Coding

914cbb12b2c3492aaa31232a11aa9c64.png

 

 

 

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值