最近观看学习了B站上的北京理工大学嵩天老师的Python网络爬虫视频,然后对之前的代码进行了一定的提高,学到可以用BeautifulSoup模块来进行网页数据爬行,通过分层的标签来搜索相应的元素,操作也变得更加快捷。
下面是我利用所学及相关网上学习,写的爬取天气网站的代码,并且调用pygal实现可视化的代码。中间遇到了一些麻烦:
①用BeautifulSoup模块锁定相关标签块的方法,利用soup.find_all(****)
②用pygal实现可视化,add的数据必须是int型数据
借了两天时间才弄出来,都是一些细节没注意,已经用标签标注,希望读者不要慌张,即使有错误,一个个寻找,一定能发现,Python的魅力就是如此,加油!
import requests
from bs4 import BeautifulSoup
import bs4
r=requests.get('http://www.weather.com.cn/weather/101250101.shtml',timeout=30)
r.raise_for_status()
r.encoding=r.apparent_encoding
data=r.text
soup=BeautifulSoup(data,'html.parser')
day_List=[]
Type_List=[]
Max_List=[]
Min_List=[]
Day_List=[]
for tr in soup.find_all('ul',class_="t clearfix"):#含有class的标签要在class前添上“_”
for day in tr.find_all('h1'):
Day_List.append(day.string)
for wea in tr.find_all('p',class_="wea"):
Type_List.append