Python爬取天气网数据并打包成exe

参考文章:
使用python爬取全国天气数据并导入MySQL数据库表
python-高级篇 在pycharm中对python项目进行打包操作

完整代码:

# 导入模块
import datetime

from bs4 import BeautifulSoup
import requests
import pymysql

# 打开数据库连接,并使用cursor()建立一个游标对象
conn = pymysql.connect(host='localhost', user='root', passwd='root', db='mysql', port=3306, charset='utf8')

cursor = conn.cursor()

# 创建request对象,指定url和请求头(user-agent),目的是为了更真实的模拟浏览器
def get_temperature(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
    }  # 设置头文件信息

    response = requests.get(url, headers=headers).content  # 提交requests.get请求,传递url和headers
    soup = BeautifulSoup(response, "lxml")  # 用Beautifulsoup 进行解析

    conmid = soup.find('div', class_='conMidtab')
    conmid2 = conmid.findAll('div', class_='conMidtab3')

    for info in conmid2:
        tr_list = info.find_all('tr')[0:]  # 使用切片取到第三个tr标签
        for index, tr in enumerate(tr_list):  # enumerate可以返回元素的位置及内容
            td_list = tr.find_all('td')
            if index == 0:
                province_name = td_list[0].text.replace('\n', '')  # 取每个标签的text信息,并使用replace()函数将换行符删除
                city_name = td_list[1].text.replace('\n', '')
                weather = td_list[5].text.replace('\n', '')
                wind = td_list[6].text.replace('\n', '')
                max = td_list[4].text.replace('\n', '')
                min = td_list[7].text.replace('\n', '')
                date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                print(province_name)
            else:
                city_name = td_list[0].text.replace('\n', '')
                weather = td_list[1].text.replace('\n', '')
                wind = td_list[2].text.replace('\n', '')
                max = td_list[3].text.replace('\n', '')
                min = td_list[6].text.replace('\n', '')
                date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                print(city_name, weather, wind, max, min, date)

            if city_name == '江阴' or city_name == '苏州':
                sql = "INSERT INTO tqyb(city, weather, wind, max, min,date) VALUES ('%s', '%s', '%s', '%s', '%s', '%s')" % (
                    city_name, weather, wind, max, min, date)
                cursor.execute(sql)

if __name__ == '__main__':
    urls = ['http://www.weather.com.cn/textFC/jiangsu.shtml']

    for url in urls:
        get_temperature(url)
    conn.commit()

在Terminal下输入:“PyInstaller -F -w *.py” 就可以制作出exe。生成的文件放在同目录dist下。

pyinstaller -F  weather.py

你可能感兴趣的:(Python爬取天气网数据并打包成exe)