爬虫实现应用了BeautifulSoup和request模块 --最后含源码
1.beautifulsoup库的简介:
Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。官方解释如下:
- Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。
- Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。然后,你仅仅需要说明一下原始编码方式就可以了。
- Beautiful Soup已成为和lxml、html6lib一样出色的python解释器,为用户灵活地提供不同的解析策略或强劲的速度。
2.request库简介:
- Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装,从而使得Pythoner进行网络请求时,变得美好了许多,使用Requests可以轻而易举的完成浏览器可有的任何操作。
- 开源地址:https://github.com/kennethreitz/requests
3.运行示例:
4.最后上源码!
from bs4 import BeautifulSoup
import requests
hot=-100
cold=100
int (hot)
int (cold)
www = 0
Q = requests.get("http://www.weather.com.cn/forecast/")
Q.encoding = "utf-8"
soup = BeautifulSoup(Q.text,"html.parser")
div = soup.find("div",id="maptabbox01")
ul = div.find("ul")
li = ul.find_all("li")
citys = []
citysname = []
for href in li:
#print(href.find("a").string)
temp=href.find("a")['href']
if temp is not None :
#print(temp.replace("1d",""))
citys.append(temp.replace("1d",""))
for mytitle in li:
temp=mytitle.find("a").string
if temp is not None :
citysname.append(temp)
i=0
for city in citys:
#print(city)
response = requests.get(city)
response.encoding = "utf-8"
soup = BeautifulSoup(response.text,"html.parser")
div = soup.find("div",id="7d")
ul = div.find("ul")
li = ul.find_all("li")
weatherForSevenDay = []
for weather in li:
temp = []
date = weather.find("h1").string
temp.append(date)
p = weather.find_all("p")
weatherDetail = p[0].string
if weatherDetail is not None :
temp.append("天气为:%s "% weatherDetail)
if p[1].find("span") is not None :
Hightemprature = p[1].find("span").string
if Hightemprature is not None:
temp.append("最高温度为:%s"% Hightemprature)
hottemp=int(Hightemprature.replace("℃",""))
if hottemp > hot:
hot=hottemp
LowTemprature = p[1].find("i").string
if LowTemprature is not None:
temp.append("最低温度为:%s "% LowTemprature)
coldtemp=int(LowTemprature.replace("℃",""))
if coldtemp < cold:
cold=coldtemp
weatherForSevenDay.append(temp)
print(citysname[i],"天气:")
for weather in weatherForSevenDay:
qaq = str(weather).replace("'","")
qaq = qaq.replace("[","")
qaq = qaq.replace("]","")
qaq = qaq.replace("(","")
qaq = qaq.replace(")","")
print(qaq)
print("\n")
i=i+1
if Hightemprature is not None :
print("最高温为:",hot,"°C 。最低温为:",cold,"°C ,请注意增减衣物。""\n\n")
print("如果想知道更多天气预报请到浏览器搜索网址http://www.weather.com.cn/forecast/")
else:
print("最低温为:",cold,"°C ,请注意增减衣物。")
print("\n")
这是我第一次写,不喜勿喷,谢谢
本文章源码纯手写,如有雷同,请@我,纯属巧合。