最近突然想学爬虫。
但是python也不太会,慢慢学咯。
这里是我的学习笔记。
这里主要参考博客http://blog.csdn.net/column/details/why-bug.html学习。
但是由于他的python是2.3版本,我安装的是python3版本。可能会出现一些问题。
这里是我查到的解决方案。
1.在学习 http://blog.csdn.net/pleasecallmewhy/article/details/8923067时,他的代码
import urllib2
response = urllib2.urlopen('http://www.baidu.com/')
html = response.read()
print html
在 python3里会出现错误
这个错误是因为 python3里的print html 需将print 的参数加上括号写为 print (html)
修改后运行,仍然会出错
这是因为在python3.3里面,用urllib.request代替urllib2
修改后的代码:
import urllib.request
response = urllib.request.urlopen('http://www.baidu.com/')
html = response.read()
print (html)
这样就能爬到百度所有的代码啦!
不满足与只打印到屏幕上,我想存在文件里,于是在程序的最后添加了代码:
f=open('baidu_url.txt','w')
f.write(html)
f.close()
然而报错
将文件以二进制方式打开就OK啦~以下是最终代码
import urllib.request
response = urllib.request.urlopen('http://www.baidu.com/')
html = response.read()
print (html)
f=open('baidu_url.txt','wb')
f.write(html)
f.close()
用火狐或是Chrome浏览器查看百度主页源代码,会发现和文件中的一样~
另外,在文件头加上
#coding:utf-8
即可看到中文的代码
所有代码:
#coding:utf-8
import urllib.request
response=urllib.request.urlopen('http://tieba.baidu.com/')
html=response.read()
print (html)
f=open('baidu.txt','wb')
f.write(html)
f.close()
这一课结束了,好开心(。◕ˇ∀ˇ◕)