本文用到Beautiful Soup和Requests两个模组。
Docs:
Beautiful Soup: http://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/#
Requests:http://cn.python-requests.org/zh_CN/latest/
实现过程:
1.原理
通过Chrome的开发者工具浏览elements
找到keyword:id="hidden_value",发现是唯一元素且显示了当天的天气情况
通过Requests请求页面,Beautiful Soup定位
2.实现中遇到的问题
使用requests模块请求的时候遇到中文都是乱码
使用Beautiful Soup模块匹配到的list怎么拆解分析到最后结果
3.解决问题
使用
requests.encoding
发现代码是ISO-8859-1格式,所以通过encoding
将格式设定在'utf-8'先用str强制转换类型再用
string.split
切割字符串
代码:
import requests
from bs4 import BeautifulSoup
import re
r = requests.get('http://www.weather.com.cn/weather/101020100.shtml')
print(r.encoding)
r.encoding = 'utf-8' #防止乱码出现
soup = BeautifulSoup(r.text, 'html.parser')
todayinfolist = soup.find_all(id="hidden_title")
str_todayinfo = str(todayinfolist[0]) #将列表元素转换为字符串
split1 = str_todayinfo.split('value="')
str_split1 = str(split1[1])
todayinfo = str_split1.split('"')
print(todayinfo[0])