首页 > 代码库 > python爬虫----(1. 基本模块)
python爬虫----(1. 基本模块)
python爬虫,web spider。爬取网站获取网页数据,并进行分析提取。
基本模块使用的是 urllib,urllib2,re,等模块
(一)基本用法,例子
(1)进行基本GET请求,获取网页html
#!coding=utf-8 import urllib import urllib2 url = ‘http://www.baidu.com/‘ # 获取请求 request = urllib2.Request(url) try: # 根据request,得到返回response response = urllib2.urlopen(request) except urllib2.HTTPError, e: if hasattr(e, ‘reason‘): print e.reason # 读取response的body html = response.read() # 读取response的headers headers = response.info()
(2)表单提交
#!coding=utf-8 import urllib2 import urllib post_url = ‘‘ post_data = urllib.urlencode({ ‘username‘: ‘username‘, ‘password‘: ‘password‘, }) post_headers = { ‘User-Agent‘: ‘Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:31.0) Gecko/20100101 Firefox/31.0‘, } request = urllib2.Request( url=post_url, data=http://www.mamicode.com/post_data,>(3)
#!coding=utf-8 import urllib2 import re page_num = 1 url = ‘http://tieba.baidu.com/p/3238280985?see_lz=1&pn=‘+str(page_num) myPage = urllib2.urlopen(url).read().decode(‘gbk‘) myRe = re.compile(r‘class="d_post_content j_d_post_content ">(.*?)</div>‘, re.DOTALL) items = myRe.findall(myPage) f = open(‘baidu.txt‘, ‘a+‘) import sys reload(sys) sys.setdefaultencoding(‘utf-8‘) i = 0 texts = [] for item in items: i += 1 print i text = item.replace(‘<br>‘, ‘‘) text.replace(‘\n‘, ‘‘).replace(‘ ‘, ‘‘) + ‘\n‘ print text f.write(text) f.close()(4)
#coding:utf-8 ‘‘‘ 模拟登陆163邮箱并下载邮件内容 ‘‘‘ import urllib import urllib2 import cookielib import re import time import json class Email163: header = {‘User-Agent‘:‘Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6‘} user = ‘‘ cookie = None sid = None mailBaseUrl=‘http://twebmail.mail.163.com‘ def __init__(self): self.cookie = cookielib.CookieJar() cookiePro = urllib2.HTTPCookieProcessor(self.cookie) urllib2.install_opener(urllib2.build_opener(cookiePro)) def login(self,user,pwd): ‘‘‘ 登录 ‘‘‘ postdata = urllib.urlencode({ ‘username‘:user, ‘password‘:pwd, ‘type‘:1 }) #注意版本不同,登录URL也不同 req = urllib2.Request( url=‘https://ssl.mail.163.com/entry/coremail/fcg/ntesdoor2?funcid=loginone&language=-1&passtype=1&iframe=1&product=mail163&from=web&df=email163&race=-2_45_-2_hz&module=&uid=‘+user+‘&style=10&net=t&skinid=null‘, data=http://www.mamicode.com/postdata,>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。