首先开始观察要爬取的网页(此处为中国天气网天气预报):
这是华北地区的天气预报网址为:http://www.weather.com.cn/textFC/hb.shtml
切换到东北地区后:
可以发现url只有textFC/后面的字符改变了,hb代表华北,db代表东北,所以由此可以建立一个url列表,只要循环遍历此表,便可以获取各个地区的天气预报网页url(由于港澳台网页结构较为特殊,此处不做处理) 。
接下来定义一个get_temperature函数来查找网页中需要的天气信息,构建一个headers参数,并提交request.get请求,接下来使用BeautifulSoup进行网页的解析。
在浏览器中按右键检查元素,观察网页结构,可以发现页面所有的城市信息及该城市的天气信息都在
打开数据库连接,并使用cursor()建立一个游标对象:
利用 cursor.execute() 函数将数据导入新建的表中:
最后,使用commit( ) 将所写的数据提交入数据库即可
然后再使用命令select * from 表名;
查看数据是否导入成功。
#导入模块
from bs4 import BeautifulSoup
import requests
import pymysql
#打开数据库连接,并使用cursor()建立一个游标对象
conn=pymysql.connect(host='localhost',user='root',passwd='niechaogang',db='ncg',port=3306,charset='utf8')
cursor=conn.cursor()
#创建request对象,指定url和请求头(user-agent),目的是为了更真实的模拟浏览器
def get_temperature(url):
urls=['http://www.weather.com.cn/textFC/hb.shtml',
'http://www.weather.com.cn/textFC/db.shtml',
'http://www.weather.com.cn/textFC/hd.shtml',
'http://www.weather.com.cn/textFC/hz.shtml',
'http://www.weather.com.cn/textFC/hn.shtml',
'http://www.weather.com.cn/textFC/xb.shtml',
'http://www.weather.com.cn/textFC/xn.shtml']
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_='conMidtab2')
for info in conmid2:
tr_list = info.find_all('tr')[2:] # 使用切片取到第三个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', '')
print(province_name)
else:
city_name = td_list[0].text.replace('\n', '')
weather = td_list[4].text.replace('\n', '')
wind = td_list[5].text.replace('\n', '')
max = td_list[3].text.replace('\n', '')
min = td_list[6].text.replace('\n', '')
print(city_name, weather, wind, max, min)
sql = "INSERT INTO tqyb(city, weather, wind, max, min) VALUES ('%s', '%s', '%s', %s, %s)" % (city_name, weather, wind, max, min)
cursor.execute(sql)
if __name__=='__main__':
for url in urls:
get_temperature(url)
conn.commit()
导入数据报错
解决方法:
1)、检查数据库的连接跟SQL插入语句是否存在问题
参考文章
2)、查看数据库的编码格式,要与导入数据的编码格式一致。
参考博客
3)、删除数据库表中的数据:
第一种:delete from tablename where 1=1;
第二种:truncate table tablename;
区别是:第二种清空表数据比较及时,能够很快地释放数据库表空间,而且不记录删除操作,自增字段还是从表建立的时候设置的初始值开始,
注意:drop table tablename;是将表删除,包括表中的内容,表的定义,数据库表空间