python抓取的一些总结

python作为爬虫的最常见语言,很有自己的优势。这里举一些常见的用法。

1,使用scrapy框架。

https://scrapy-chs.readthedocs.io/zh_CN/0.24/intro/tutorial.html

2, 纯脚本

lib库

from concurrent.futures import ThreadPoolExecutor

from bs4 import BeautifulSoup

import Queue, time, random

import requests

提供一个比较粗糙的代码,使用到了python代理,queue,多线程,BeautifulSoup。最终print方法应该用线程锁避免打印错误。


#coding=utf-8
import requests
from concurrent.futures import ThreadPoolExecutor
import Queue, time, random
#import pymysql
from bs4 import BeautifulSoup
import re
import urllib
import urllib2
import gzip
import cStringIO
import datetime
import json
from StringIO import StringIO
import threading

import base64

index_url = 'https://www.juzimi.com/alltags'
page_url = 'https://www.juzimi.com/alltags?page=%s'

task_queue = Queue.Queue()

has_words = []
has_words_value = {}

lock=threading.Lock()

ip = ""
def getIp() :
global ip

url = 'http://s.zdaye.com/?api=201903221353043521&count=1&px=2'
ipret = curl(url, '', False, False)
time.sleep(5)
print "get ip:" + str(ipret)
ip = str(ipret)
def curl(url, data = '', isCompress = False, use_ip = True):

global ip
if(data):
data = urllib.urlencode(data)
else:
data = None
#headers = {"method":"GET","user-agent":self.ua,"Referer":self.refer, "Cookie":self.cookie, "Upgrade-Insecure-Requests": 1,"Accept-Encoding": "gzip, deflate, br"}
headers = {"method":"GET","Accept-Encoding": "gzip, deflate, br", "user-agent" : "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36"}

try :

#代理代码
if(use_ip) :
opener = urllib2.build_opener(urllib2.ProxyHandler({"https" : ip}))
urllib2.install_opener(opener)

request = urllib2.Request(url, data, headers)
response = urllib2.urlopen(request, timeout=10)

#response = opener.open(request)
if(isCompress) :
buf = StringIO(response.read())
data = gzip.GzipFile(fileobj=buf)
return data.read()
return response.read()

except :
exit()
getIp()
print "get ip retry"
self.curl(url, data, isCompress, use_ip)

#exit()

def setTaskR() :
task_queue.put({'url':'https://www.juzimi.com/tags/%E6%96%B0%E8%AF%97', 'title':'诗词'})

def setTask() :
#for i in range(0, 12) :
for i in range(0, 12) :
url = page_url % (i)
content = curl(url, '', True)
#print url
soup = BeautifulSoup(content, "html.parser")
span = soup.findAll('div',{'class':'views-field-name'})
for tmp in span :
data = {}
href = tmp.find('a').get('href')
title = tmp.find('a').get('title')
data = {"url":"https://www.juzimi.com" + href, "title" : title}
print data
task_queue.put(data)
#print tmp.get('title')
time.sleep(1)

def getFile() :

global has_words
global has_words_value

for line in open('word.log') :
if(line.find('juzimi.com') != -1) :
continue
line = line.split(":", 1)
if(len(line) > 1 and line[1] == 'test') :
continue

#print line[0]
if(not line[0] in has_words) :
has_words.append(line[0])
has_words_value[line[0]] = 1
#print line[0]
else :
has_words_value[line[0]] = has_words_value[line[0]] + 1
has_words = []
for k in has_words_value:
if(has_words_value[k] > 100) :
has_words.append(k)
for line in open('word.url') :
lines = eval(line)
url = lines['url']
title = lines['title'].encode('utf-8')
if(title in has_words) :
continue
task_queue.put(lines)

#runTask()
sleep_time = random.randint(30,60)
#time.sleep(sleep_time)
#time.sleep(60)

def runTask() :
while(not task_queue.empty()) :
data = task_queue.get()
printinfo =[]
hotword = data['title']
url = data['url']
hotword = hotword.encode('utf-8')
#print url
lastIndex = 0
content = curl(url, '', True)
#content = re.sub(r'\n|&nbsp|\xa0|\\xa0|\u3000|\\u3000|\\u0020|\u0020', '', str(content))
content = content.replace('<br/>', '')
content = content.replace('\r', ' ')
soup = BeautifulSoup(content, "html.parser")
last = soup.find('li', {'class', 'pager-last'})
if (not last) :

last = soup.findAll('li', {'class' : 'pager-item'})
if(not last) :
print "get empty:" + url
continue
for tmp in last :
if(int(tmp.text) > lastIndex) :
#print int(tmp.text)
lastIndex = int(tmp.text)
else :
lastIndex = last.text

span = soup.findAll('div',{'class', 'views-field-phpcode-1'})

if(not span) :
print "get empty:" + url
continue

#print url
for tmp in span :
words = tmp.findAll('a')
for word in words :
#printinfo.append({'hotword' : hotword, 'content' : word.text.encode('utf-8')})
print hotword + ":" + word.text.encode('utf-8')
#time.sleep(3)
sleep_time = random.randint(10,20)
#time.sleep(sleep_time)
for i in range(1, int(lastIndex)) :

url = "https://www.juzimi.com/tags/" +hotword + "?page=" + str(i)
#ret = getContent(url, hotword)

t = threading.Thread(target=getContent, args=(url, hotword))
t.start()
"""
for tmp in ret:
printinfo.append(tmp)
"""

"""
for tmp in printinfo :
print tmp['hotword'] + ":" + tmp['content']
"""

def getContent(url, hotword) :
printinfo =[]
#print url
content = curl(url, '', True)
#content = re.sub(r'\n|&nbsp|\xa0|\\xa0|\u3000|\\u3000|\\u0020|\u0020', '', str(content))
content = content.replace('<br/>', '')
content = content.replace('\r', ' ')
soup = BeautifulSoup(content, "html.parser")
last = soup.find('li', {'class', 'pager-last'})
span = soup.findAll('div',{'class', 'views-field-phpcode-1'})
for tmp in span :
words = tmp.findAll('a')
for word in words :
#printinfo.append({'hotword' : hotword, 'content' : word.text.encode('utf-8')})
print hotword + ":" + word.text.encode('utf-8')
sleep_time = random.randint(20,30)
#time.sleep(sleep_time)
#return printinfo

getIp()

getFile()

"""

#setTaskR()
#runTask()
#exit()
"""
executor = ThreadPoolExecutor(max_workers = 50)
#executor.submit(runTask)
#exit()
for i in range(0, 20) :
executor.submit(runTask)

&nbsp;

 

[转]python中str字符串和unicode对象字符串的拼接问题

一个很基本的问题,遇到了,这里记录下

str字符串

s = ‘中文’ # s: <type ‘str’>
s是个str对象,中文字符串。存储方式是字节码。字节码是怎么存的:

如果这行代码在python解释器中输入&运行,那么s的格式就是解释器的编码格式;

如果这行代码是在源码文件中写入、保存然后执行,那么解释器载入代码时就将s初始化为文件指定编码(比如py文件开头那行的utf-8);

unicode对象字符串

unicode是一种编码标准,具体的实现可能是utf-8,utf-16,gbk等等,这就是中文字符串和unicode有密切关系的原因。

python内部使用两个字节存储一个unicode对象(unicode对象并不只能是字符串,这两个字节还可以存其他内容),为什么要用unicode而不用str呢,因为中文转码的缘故,因为unicode的优点是便于跨平台。

s1 = u’中文’ # s1: <type ‘unicode’>
s2 = unicode(‘中文’, ‘utf-8’) # utf8是在指定解码方式, s2: <type ‘unicode’>
str字符串和unicode字符串拼接

只要注意正确的decode、encode方式,统一编码后就能顺利地拼接了。

# -*- coding: utf-8 -*-

s1 = ‘中文’
s2 = u’你好’
print s1 + unicode(s2, ‘utf-8’) # 中文你好
print s1 + s2.decode(‘utf-8’) # 中文你好
print s1.encode(‘utf-8’) + s2 # 中文你好

print type(s1) # <type ‘str’>
print type(s2) # <type ‘unicode’>
print type(s1.decode(‘utf-8’)) # <type ‘unicode’>
print type(s2.encode(‘utf-8’)) # <type ‘str’>
对于str要注意当前环境编码方式,也许是控制台那种设定好了的,也许是你自己在代码中指定的。(看你的代码是在哪里敲的了)
对于unicode对象,一般都是decode得到的,像直接【u’你好’】这种其实不是很常见,所以要注意字符串来源是什么编码,比如从gbk文件或utf8文件中读入的。
———————
作者:Joy_Shen
来源:CSDN
原文:https://blog.csdn.net/index20001/article/details/78974814
版权声明:本文为博主原创文章,转载请附上博文链接!

一款跨平台的Web目录扫描工具

工具是由安全盒子王松编写 是用Python编写的  其中包含脚本识别 后台地址 以及乌云抓的常见漏洞url

这对于Ubuntu系统的用户 特别方便  Windows上也有很多的扫描目录的好工具 比如御剑 wwwscan 等等很多

我自己加入了一点点字典

亲测

从github上下载即可

[AppleScript] 纯文本查看 复制代码
1
2
3
4
5
git clone [url]https://github.com/Strikersb/webdirscan[/url]
cd webdirscan
python webdirscan.py  url

报错的话 安装的第三方Python模块成功解决

[AppleScript] 纯文本查看 复制代码
1
pip install requests

运行图如下

[AppleScript] 纯文本查看 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
root@xaiSec:/home/hacker# cd webdirscan
root@xaiSec:/home/hacker/webdirscan# python webdirscan.py -h
usage: webdirscan.py [-h] [-d SCANDICT] [-o SCANOUTPUT] [-t THREADNUM]
                     scanSite
positional arguments:
  scanSite              The website to be scanned
optional arguments:
  -h, --help            show this help message and exit
  -d SCANDICT, --dict SCANDICT
                        Dictionary for scanning
  -o SCANOUTPUT, --output SCANOUTPUT
                        Results saved files
  -t THREADNUM, --thread THREADNUM
                        Number of threads running the program
root@xaiSec:/home/hacker/webdirscan#

翻译后

[AppleScript] 纯文本查看 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
用法:webdirscan.py [-h] [-d SCANDICT] [-o SCANOUTPUT] [-t THREADNUM]
                      scanSite
位置参数:
   scanSite要扫描的网站
可选参数:
   -h,--help显示此帮助消息并退出
   -d SCANDICT,--dict SCANDICT
                         扫描词典
   -o SCANOUTPUT,--output SCANOUTPUT
                         结果保存的文件
   -t THREADNUM, - thread THREADNUM
                         运行程序的线程数

首先我们先来扫描一个网站 比如我们来扫描下百度= =  嘿嘿
输出结果为以下

[AppleScript] 纯文本查看 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
root@xaiSec:/home/hacker/webdirscan# python webdirscan.py [url]www.baidu.com[/url]
Dirscan is running!
Scan target: [url]http://www.baidu.com[/url]
Total Dictionary: 85025
[200]http://www.baidu.com/robots.txt
[200]http://www.baidu.com/index.htm
[200]http://www.baidu.com/index.php
[200]http://www.baidu.com/index.html
[200]http://www.baidu.com/index.html
[200]http://www.baidu.com/cache/
[200]http://www.baidu.com/index.htm
[200]http://www.baidu.com/robots.txt

 

whistle代理调试工具

首先看官方文档:http://wproxy.org/whistle/

whistle(读音[ˈwɪsəl],拼音[wēisǒu])基于Node实现的跨平台web调试代理工具,类似的工具有Windows平台上的Fiddler,主要用于查看、修改HTTP、HTTPS、Websocket的请求、响应,也可以作为HTTP代理服务器使用,不同于Fiddler通过断点修改请求响应的方式,whistle采用的是类似配置系统hosts的方式,一切操作都可以通过配置实现,支持域名、路径、正则表达式、通配符、通配路径等多种匹配方式,且可以通过Node模块扩展功能

这里简单介绍下安装

安装启动

安装启动whistle,需要以下四个步骤: 安装Node安装whistle启动whistle配置代理

1. 安装Node

whistle支持v0.10.0以上版本的Node,为获取更好的性能,推荐安装最新版本的Node。

如果你的系统已经安装了v0.10.0以上版本的Node,可以忽略此步骤,直接进入安装whistle的步骤,否则:

  1. Windows或Mac系统,访问https://nodejs.org/,安装LTS版本的Node,默认安装即可。
  2. Linux下推荐使用源码安装: 从Node官网下载最新版的Source Code(或者用wget命令下载),解压文件(tar -xzvf node-vx.y.z.tar.gz)后进入解压后的根目录(node-vx.y.z),依次执行./configure./make./make install

安装完Node后,执行下面命令,查看当前Node版本

$ node -v
v4.4.0

如果能正常输出Node的版本号,表示Node已安装成功(Windows系统可能需要重新打开cmd)。

2. 安装whistle

Node安装成功后,执行如下npm命令安装whistle (Mac或Linux的非root用户需要在命令行前面加sudo,如:sudo npm install -g whistle

$ npm install -g whistle

npm默认镜像是在国外,有时候安装速度很慢或者出现安装不了的情况,如果无法安装或者安装很慢,可以使用taobao的镜像安装:

$ npm install cnpm -g --registry=https://registry.npm.taobao.org
$ cnpm install -g whistle

或者直接指定镜像安装:
$ npm install whistle -g --registry=https://registry.npm.taobao.org

whistle安装完成后,执行命令 whistle help 或 w2 help,查看whistle的帮助信息

$ w2 help

 Usage: whistle <command> [options]


  Commands:

    status              Show the running status of whistle
    use/add [filepath]  Set rules from a specified js file (.whistle.js by default)
    run                 Start a front service
    start               Start a background service
    stop                Stop current background service
    restart             Restart current background service
    help                Display help information

  Options:

    -h, --help                                      output usage information
    -D, --baseDir [baseDir]                         set the configured storage root path
    -z, --certDir [directory]                       set custom certificate store directory
    -l, --localUIHost [hostname]                    set the domain for the web ui of whistle (local.whistlejs.com by default)
    -L, --pluginHost [hostname]                     set the domain for the web ui of plugin  (as: "script=a.b.com&vase=x.y.com")
    -n, --username [username]                       set the username to access the web ui of whistle
    -w, --password [password]                       set the password to access the web ui of whistle
    -N, --guestName [username]                      set the the guest name to access the web ui of whistle (can only view the data)
    -W, --guestPassword [password]                  set the guest password to access the web ui of whistle (can only view the data)
    -s, --sockets [number]                          set the max number of cached long connection on each domain (60 by default)
    -S, --storage [newStorageDir]                   set the configured storage directory
    -C, --copy [storageDir]                         copy the configuration of the specified directory to a new directory
    -c, --dnsCache [time]                           set the cache time of DNS (30000ms by default)
    -H, --host [host]                               set the listening host (INADDR_ANY by default)
    -p, --port [port]                               set the listening port (8899 by default)
    -P, --uiport [uiport]                           set the listening port of whistle (8900 by default)
    -m, --middlewares [script path or module name]  set the express middlewares loaded at startup (as: xx,yy/zz.js)
    -M, --mode [mode]                               set the way of starting the whistle mode (as: pureProxy|debug|multiEnv)
    -u, --uipath [script path]                      set the path of custom web ui
    -t, --timeout [ms]                              set the request timeout (66000ms by default)
    -e, --extra [extraData]                         set the extra parameters for plugin
    -f, --secureFilter [secureFilter]               set the path of secure filter
    -R, --reqCacheSize [reqCacheSize]               set the cache size of request data (600 by default)
    -F, --frameCacheSize [frameCacheSize]           set the cache size of webSocket and socket's frames (512 by default)
    -V, --version                                   output the version number

如果能正常输出whistle的帮助信息,表示whistle已安装成功。

3. 启动whistle

最新版本的whistle支持三种等价的命令whistlew2wproxy

启动whistle:

$ w2 start

Note: 如果要防止其他人访问配置页面,可以在启动时加上登录用户名和密码 -n yourusername -w yourpassword

重启whsitle:

$ w2 restart

停止whistle:

$ w2 stop

调试模式启动whistle(主要用于查看whistle的异常及插件开发):

$ w2 run

启动完whistle后,最后一步需要配置代理。

4. 配置代理

配置信息
  1. 代理服务器:127.0.0.1 (如果部署在远程服务器或虚拟机上,改成对应服务器或虚拟机的ip即可)
  2. 默认端口:8899 (如果端口被占用,可以在启动是时通过 -p 来指定新的端口,更多信息可以通过执行命令行 w2 help (v0.7.0及以上版本也可以使用w2 help) 查看)

勾选上 对所有协议均使用相同的代理服务器

代理配置方式(把上面配置信息配置上即可)
  1. 全局代理:直接配置系统代理:
    • Windows
    • Mac: System Preferences > Network > Advanced > Proxies > HTTP or HTTPS
       

      * Linux: Settings > Network > VPN > Network Proxy > Manual

       
  2. 浏览器代理:安装浏览器代理插件 (推荐)
    • 安装Chrome代理插件:推荐安装SwitchyOmega

      * Firefox: 地址栏输入访问 `about:preferences`,找到 `Network Proxy`,选择 `手动代理配置(Manual proxy configuration)`,输入代理服务器地址、端口,保存

       
  3. 移动端需要在设置中配置当前Wi-Fi的代理,以 iOS 为例:

PS: 如果配置完代理,手机无法访问,可能是whistle所在的电脑防火墙限制了远程访问whistle的端口,关闭防火墙或者设置白名单:http://jingyan.baidu.com/article/870c6fc317cae7b03ee4be48.html

访问配置页面

启动whistle及配置完代理后,用Chrome浏览器(由于css兼容性问题界面只支持Chrome浏览器)访问配置页面,如果能正常打开页面,whistle安装启动完毕,可以开始使用。

可以通过以下两种方式来访问配置页面: