1.基础方法
url = “http://www.baidu.com”
html = urllib.urlopen(url) #打开网页,获取类对象文件
content = html.read() #读网页内容
print html.getcode()#获取网页状态码 404网页不存在 200可以正常访 问 301重定向 403禁止访问
#print html.info() #get header info
html.geterl() #返回所打开网页的url地址
2.下载网页
import urllib
url = "http://www.baidu.com"
urllib.urlretrieve(url,"baidu.txt")
urlretrieve函数有两个参数,第一个参数为url地址,第二个参数为路径名
3.下载网页上的图片
参考网址:http://www.cnblogs.com/fnng/p/3576154.html
#coding = utf-8
import urllib
import re
def getHtml(url):
page = urllib.urlopen(url)
html = page.read()
page.close()
return html
def getImg(html):
reg = r'src="(.+?\.png)"'
imgre = re.compile(reg)
imglist = re.findall(imgre,html)
x = 0
for imgurl in imglist:
urllib.urlretrieve(imgurl,'%s.jpg'%x)
x+=1
html = getHtml("http://pic.sogou.com/d?query=%CD%BC%C6%AC&mood=0&st=255&picformat=0&mode=255&di=0&did=3#did2")
print getImg(html)
4.python爬虫实例
http://blog.youkuaiyun.com/bo_wen_/article/details/50868339#comments
http://blog.youkuaiyun.com/bo_wen_/article/details/50911423
http://blog.youkuaiyun.com/bo_wen_/article/details/50927688
http://www.guadong.net/article/aKoDzYHi.html
Beautiful Soup 4.2.0 文档 中文版
Beautiful Soup 4.2.0 文档 英文版
5.使用Beautifulsoup库
import urllib
from bs4 import BeautifulSoup
html = urllib.urlopen("http://www.dr-chuck.com").read()
soup = BeautifulSoup(html)
tags = soup('a')
for tag in tags:
print tag.get('href',None)
上面这段代码可以输出所有的网页上面的链接
python学习爬虫系列教程:http://cuiqingcai.com/1052.html