python--爬虫1

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值