我最近学了两天python,自己写了网络爬虫的例子。
python : 3.5版
IDE : pycharm 5.0.4
使用的软件包可以在pycharm上下载。
文件默认设置-默认项目项目解释器
选择python版本,然后单击右侧的加号以安装所需的软件包
我选择的网站是中国天气网苏州天气,打算抓住最近7天的天气和最高/最低气温
33558 www.weather.com.cn/weather/101190401.shtml
在程序的开头添加。
# coding : UTF-8现在,您可以告诉解释器此py程序已用utf-8编码,并且源程序可以包含中文。
要引用的软件包:
importrequestsimportcsvimportrandomimporttimeimportsocketimporthttp.client # import urllib.requestfrombs4importbeautifulsoulsous
CSV :向CSV文件写入数据
随机:取随机数
time :时间相关操作
socket和http.client在此仅用于异常处理
BeautifulSoup :用于获取源代码中相应标记的内容,而不是正则表达式
ullib.request :这是另一种捕获网页html源代码的方法,但不如requests有用。 (我第一个用的是这个)
获取网页中的html代码:
efget_content(URL,data=None ) : header={ ' accept ' : ' text/html,application/xhtml xml,aplication q 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 ' } time out=random.choice (range ) 80,180 ) whh headers=header,timeout=timeout ) rep.encoding='utf-8' data,header (# response=urllib.request.urlopen ) timeout=timeout ) # html1=response.read ).decode ) ' errors='ignore ' ) # response.close () break # except urllib e ) tttperrrorase 10 ) ) # except urllib.request.urlerrorase : # print (' 2: ', e ) #time.sleep(Random.choice ) range ) )5 10 ) ) exceptsocket.time out ase : print (' 3: ',e ) time.sleret 15 ) ) ) exceptsoice e ) time.sleep (random.choice (range (20,60 ) ) except http.client.badstatuslinease 330
print( '6:', e) time.sleep(random.choice(range(5, 15))) return rep.text # return html_textheader是requests.get的一个参数,目的是模拟浏览器访问
header 可以使用chrome的开发者工具获得,具体方法如下:
打开chrome,按F12,选择network
重新访问该网站,找到第一个网络请求,查看它的header
timeout是设定的一个超时时间,取随机数是因为防止被网站认定为网络爬虫。
然后通过requests.get方法获取网页的源代码、
rep.encoding = ‘utf-8’是将源代码的编码格式改为utf-8(不该源代码中中文部分会为乱码)
下面是一些异常处理
返回 rep.text
获取html中我们所需要的字段:
这里我们主要要用到BeautifulSoup
BeautifulSoup 文档http://www.crummy.com/software/BeautifulSoup/bs4/doc/
首先还是用开发者工具查看网页源码,并找到所需字段的相应位置
找到我们需要字段都在 id = “7d”的“div”的ul中。日期在每个li中h1 中,天气状况在每个li的第一个p标签内,最高温度和最低温度在每个li的span和i标签中。
感谢Joey_Ko指出的错误:到了傍晚,当天气温会没有最高温度,所以要多加一个判断。
代码如下:
写入文件csv:
将数据抓取出来后我们要将他们写入文件,具体代码如下:
主函数:
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')然后运行一下:
生成的weather.csv文件如下:
总结一下,从网页上抓取内容大致分3步:
1、模拟浏览器访问,获取html源代码
2、通过正则匹配,获取指定标签中的内容
3、将获取到的内容写到文件中
刚学python爬虫,可能有些理解有错误的地方,请大家批评指正,谢谢!