如何爬虫 爬虫怎么做( 三 )


forcontent incontent_ul:
try:
weather = {}
weather[ 'day'] = content.find( 'h1').text
weather[ 'temperature'] = content.find(
'p', class_= 'tem').span.text + content.find(
'p', class_= 'tem').em.text
weather_list.append(weather)
except:
print( '查询不到')
print(weather_list)
同样的话不说第二遍 , 我们要写好注释 。在声明完数组后 , 我们就可调用刚才封装好的请求函数来请求我们要的URL并返回一个页面文件 , 接下来就是用Beautifulsoup4里面的语法 , 用lxml来解析我们的网页文件 。
你们可以用
soup = bs4.BeautifulSoup(html, 'lxml')
print(soup)
就可以看到整个HTML结构出现在你眼前 , 接下来我就们就根据上面整理出来的标签结构来找到我们要的信息

如何爬虫 爬虫怎么做

文章插图
content_ul = soup.find( 'div', class_= 't').find_all( 'li')
具体方法 , 要熟读文档 , 我们找到所有的li后会返回一个这样的结构
这是一个数组的格式 , 然后我们遍历它 , 构造一个字典 , 我们对于的操作字典建立'day','temperature'键值对
forcontent incontent_ul:
try:
weather = {}
weather[ 'day'] = content.find( 'h1').text
weather[ 'temperature'] = content.find(
'p', class_= 'tem').span.text + content.find(
'p', class_= 'tem').em.text
weather_list.append(weather)
except:
print( '查询不到')
print(weather_list)
较后输出
附上完整代码:
'''
抓取每天的天气数据
python 3.6.2
url:http://www.weather.com.cn/weather1d/101190401.shtml
'''
importjson
importrequests
importbs4
defget_html(url):
'''
封装请求
'''
headers = {
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
'ContentType':
'text/html; charset=utf-8',
'Accept-Encoding':
'gzip, deflate, sdch',
'Accept-Language':
'zh-CN,zh;q=0.8',
'Connection':
'keep-alive',
}
try:
htmlcontet = requests.get(url, headers=headers, timeout= 30)
htmlcontet.raise_for_status()
htmlcontet.encoding = 'utf-8'
returnhtmlcontet.text
except:
return" 请求失败 "
defget_content(url):
'''
抓取页面天气数据
'''
weather_list = []
html = get_html(url)
soup = bs4.BeautifulSoup(html, 'lxml')
content_ul = soup.find( 'div', class_= 't').find( 'ul', class_= 'clearfix').find_all( 'li')
forcontent incontent_ul:
try:
weather = {}
weather[ 'day'] = content.find( 'h1').text
weather[ 'temperature'] = content.find(
'p', class_= 'tem').span.text + content.find(
'p', class_= 'tem').em.text
weather_list.append(weather)
except:
print( '查询不到')
print(weather_list)
if__name__ == '__main__':
url = 'http://www.weather.com.cn/weather1d/101190401.shtml'
【如何爬虫 爬虫怎么做】get_content(url)