python 爬虫笔记1

   最近突然想学爬虫。

   但是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()


这一课结束了,好开心(。◕ˇ∀ˇ◕)


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值