鱼C论坛

 找回密码
 立即注册
查看: 1340|回复: 0

[作品展示] 用bs4爬中国天气网

[复制链接]
发表于 2020-4-12 22:01:28 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. import requests
  2. from bs4 import BeautifulSoup
  3. def parse_page(url):#解析url页面函数
  4.     headers ={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0'}
  5.     response = requests.get(url,headers = headers)
  6.     #print(response.content.decode('utf-8'))#当解码之后的页面有乱码说明用response.test()猜错了解码方式,则应该改成response.content.decode('utf-8')
  7.     text = response.content.decode('utf-8')
  8.     soup = BeautifulSoup(text,'lxml')
  9.     conMidtab =soup.find('div',class_ = 'conMidtab')
  10.     tables = conMidtab.find_all('table')
  11.     for table in tables:
  12.         trs = table.find_all('tr')[2:]
  13.         for tr in trs:
  14.             tds =tr.find_all('td')
  15.             city_td = tds[0]
  16.             city = list(city_td.stripped_strings)[0]
  17.             temp_td = tds[-2]
  18.             min_temp =list(temp_td.stripped_strings)[0]
  19.             print({'city':city,'min_temp':min_temp})
  20. def main():
  21.     url = 'http://www.weather.com.cn/textFC/hb.shtml'
  22.     parse_page(url)

  23. if __name__ == '__main__':
  24.     main()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-13 21:59

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表