python爬虫程序_怎样制作一个Python爬虫——第一个爬虫小程序

0383f90f28f0c9d6b83ab7531c3d40ab.png

一、页面获取

首先我们需要用到以下几个库

import requestsimport csvimport randomimport timeimport socketimport http.clientfrom bs4 import BeautifulSoup

在python3中,安装库在windows及linux环境下均可以使用以下命令进行安装

例: pip3 install requests

requests:用来抓取网页的html源代码

csv:将数据写入到csv文件中

random:取随机数

time:时间相关操作

socket和http.client 在这里只用于异常处理

BeautifulSoup:用来代替正则式取源码中相应标签中的内容,将内容以合适的方法输出。

以下是获取网页内容的代码

def get_content(url , data = None):    header={        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',        'Accept-Encoding': 'gzip, deflate, sdch',        'Accept-Language': 'zh-CN,zh;q=0.8',        'Connection': 'keep-alive',        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'    }    timeout = random.choice(range(80, 180))    while True:        try:            rep = requests.get(url,headers = header,timeout = timeout)            rep.encoding = 'utf-8'            # req = urllib.request.Request(url, data, header)            # response = urllib.request.urlopen(req, timeout=timeout)            # html1 = response.read().decode('UTF-8', errors='ignore')            # response.close()            break        # except urllib.request.HTTPError as e:        #         print( '1:', e)        #         time.sleep(random.choice(range(5, 10)))        #        # except urllib.request.URLError as e:        #     print( '2:', e)        #     time.sleep(random.choice(range(5, 10)))        except socket.timeout as e:            print( '3:', e)            time.sleep(random.choice(range(8,15)))        except socket.error as e:            print( '4:', e)            time.sleep(random.choice(range(20, 60)))        except http.client.BadStatusLine as e:            print( '5:', e)            time.sleep(random.choice(range(30, 80)))        except http.client.IncompleteRead as e:            print( '6:', e)            time.sleep(random.choice(range(5, 15)))    return rep.text    # return html_text

header是requests.get的一个参数,目的是模拟浏览器访问,使用浏览器按下F12即可获取header信息。

二、获取网页中我们需要的字段

代码如下

def get_data(html_text):    final = []    bs = BeautifulSoup(html_text, "html.parser")  # 创建BeautifulSoup对象    body = bs.body # 获取body部分    data = body.find('div', {'id': '7d'})  # 找到id为7d的div    ul = data.find('ul')  # 获取ul部分    li = ul.find_all('li')  # 获取所有的li    for day in li: # 对每个li标签中的内容进行遍历        temp = []        date = day.find('h1').string  # 找到日期        temp.append(date)  # 添加到temp中        inf = day.find_all('p')  # 找到li中的所有p标签        temp.append(inf[0].string,)  # 第一个p标签中的内容(天气状况)加到temp中        if inf[1].find('span') is None:            temperature_highest = None # 天气预报可能没有当天的最高气温(到了傍晚,就是这样),需要加个判断语句,来输出最低气温        else:            temperature_highest = inf[1].find('span').string  # 找到最高温            temperature_highest = temperature_highest.replace('℃', '')  # 到了晚上网站会变,最高温度后面也有个℃        temperature_lowest = inf[1].find('i').string  # 找到最低温        temperature_lowest = temperature_lowest.replace('℃', '')  # 最低温度后面有个℃,去掉这个符号        temp.append(temperature_highest)   # 将最高温添加到temp中        temp.append(temperature_lowest)   #将最低温添加到temp中        final.append(temp)   #将temp加到final中    return final

三、写入文件csv

def write_data(data, name):    file_name = name    with open(file_name, 'a', errors='ignore', newline='') as f:            f_csv = csv.writer(f)            f_csv.writerows(data)

四、主函数

if __name__ == '__main__':    url ='http://www.weather.com.cn/weather/101190401.shtml'    html = get_content(url)    result = get_data(html)    write_data(result, 'weather.csv')
ba381ea08bf621a7c90263925f5bd980.png

这样就可以生成一个简易的用来获取天气情况的小爬虫了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值