python爬虫(1)-使用requests和beautifulsoup库爬取中国天气网

python爬虫(1)-使用requests和beautifulsoup库爬取中国天气网

使用工具及准备

python3.7(python3以上都可以)
pycharm IDE (笔者习惯使用pycharm,也可以使用其他的)
URL: http://www.weather.com.cn/weather/101230101.shtml
beautifulsoup4、requests、lxml库(pip3 install beautifulsoup4,pip3 install requests)

重点来了

(1)因为beautifulsoup要传入的是Unicode类型数据,所以首先要得到网页的纯文本,这就会用到requests库了,先利用requests的text得到纯文本

利用requests的get()函数发送get请求,get函数可以接受数个参数,详情看http://docs.python-requests.org/zh_CN/latest/user/quickstart.html,我们这里就用两个参数,URL(请求地址)以及headers(特别注意,requests库默认的编码方式是Unicode编码,但是此网站是utf-8编码,所以要指定一下编码方式)

import requests

url = 'http://www.weather.com.cn/weather/101230101.shtml'

header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/69.0.3486.0 Safari/537.36'}

response = requests.get(url=url, headers=header)
response.encoding = 'utf-8'

print(response.text)

输出如下:
在这里插入图片描述

(2)得到纯文本后,就可以利用BS库进行解析了,这里用的解析器是lxml,也可以用默认的

import requests
from bs4 import BeautifulSoup
url = 'http://www.weather.com.cn/weather/101230101.shtml'

header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/69.0.3486.0 Safari/537.36'}

response = requests.get(url=url, headers=header)
response.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'lxml')
print(soup)

输出和上边应该是一样的

(3)接下来就用BS的特性来定位元素了以及输出一些标签,在这里简单说一下,BS库定位的方式,可以利用div,a等标签定位元素,同时也能加上属性class或者id进行更加准确的定位,关于BS的定位方式,详解请看https://blog.csdn.net/love666666shen/article/details/77512353

weather = soup.find('ul', class_='t clearfix')
# 直接输出定位候的元素
print(weather)

# 输出纯文本
print(weather.text)

# 去除换行符等
print(str(weather.text).replace('\n', ''))

输出结果:
title标签
在这里插入图片描述
weather
weather
weather.text
weathwer.text
str(weather.text).replace(’\n’, ‘’)
在这里插入图片描述

到此此次任务宣布结束,欢迎留言指教!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值