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;

 

[抓]反击爬虫,前端工程师的脑洞可以有多大?

原文链接:https://juejin.im/entry/59deb55951882578c2084a63

1. 前言

对于一张网页,我们往往希望它是结构良好,内容清晰的,这样搜索引擎才能准确地认知它。
而反过来,又有一些情景,我们不希望内容能被轻易获取,比方说电商网站的交易额,教育网站的题目等。因为这些内容,往往是一个产品的生命线,必须做到有效地保护。这就是爬虫与反爬虫这一话题的由来。

2. 常见反爬虫策略

但是世界上没有一个网站,能做到完美地反爬虫。

如果页面希望能在用户面前正常展示,同时又不给爬虫机会,就必须要做到识别真人与机器人。因此工程师们做了各种尝试,这些策略大多采用于后端,也是目前比较常规单有效的手段,比如:

  • User-Agent + Referer检测
  • 账号及Cookie验证
  • 验证码
  • IP限制频次

而爬虫是可以无限逼近于真人的,比如:

  • chrome headless或phantomjs来模拟浏览器环境
  • tesseract识别验证码
  • 代理IP淘宝就能买到

所以我们说,100%的反爬虫策略?不存在的。
更多的是体力活,是个难易程度的问题。

不过作为前端工程师,我们可以增加一下游戏难度,设计出一些很(sang)有(xin)意(bing)思(kuang)的反爬虫策略。

3. 前端与反爬虫

3.1 font-face拼凑式

例子:猫眼电影

猫眼电影里,对于票房数据,展示的并不是纯粹的数字。
页面使用了font-face定义了字符集,并通过unicode去映射展示。也就是说,除去图像识别,必须同时爬取字符集,才能识别出数字。

并且,每次刷新页面,字符集的url都是有变化的,无疑更大难度地增加了爬取成本。

3.2 background拼凑式

例子:美团

与font的策略类似,美团里用到的是background拼凑。数字其实是图片,根据不同的background偏移,显示出不同的字符。

并且不同页面,图片的字符排序也是有区别的。不过理论上只需生成0-9与小数点,为何有重复字符就不是很懂。

页面A:

页面B:

3.3 字符穿插式

例子:微信公众号文章

某些微信公众号的文章里,穿插了各种迷之字符,并且通过样式把这些字符隐藏掉。
这种方式虽然令人震惊…但其实没有太大的识别与过滤难度,甚至可以做得更好,不过也算是一种脑洞吧。

对了,我的手机流量可以找谁报销吗?

3.4 伪元素隐藏式

例子:汽车之家

汽车之家里,把关键的厂商信息,做到了伪元素的content里。
这也是一种思路:爬取网页,必须得解析css,需要拿到伪元素的content,这就提升了爬虫的难度。

3.5 元素定位覆盖式

例子:去哪儿

还有热爱数学的去哪儿,对于一个4位数字的机票价格,先用四个i标签渲染,再用两个b标签去绝对定位偏移量,覆盖故意展示错误的i标签,最后在视觉上形成正确的价格…

这说明爬虫会解析css还不行,还得会做数学题。

3.6 iframe异步加载式

例子:网易云音乐

网易云音乐页面一打开,html源码里几乎只有一个iframe,并且它的src是空白的:about:blank。接着js开始运行,把整个页面的框架异步塞到了iframe里面…

不过这个方式带来的难度并不大,只是在异步与iframe处理上绕了个弯(或者有其他原因,不完全是基于反爬虫考虑),无论你是用selenium还是phantom,都有API可以拿到iframe里面的content信息。

3.7 字符分割式

例子:全网代理IP

在一些展示代理IP信息的页面,对于IP的保护也是大费周折。

他们会先把IP的数字与符号分割成dom节点,再在中间插入迷惑人的数字,如果爬虫不知道这个策略,还会以为自己成功拿到了数值;不过如果爬虫注意到,就很好解决了。

3.8 字符集替换式

例子:去哪儿移动侧

同样会欺骗爬虫的还有去哪儿的移动版。

html里明明写的3211,视觉上展示的却是1233。原来他们重新定义了字符集,3与1的顺序刚好调换得来的结果…

知乎日报搜索小应用

博主每天都要刷知乎日报,感觉里面的内容很不错,但是有时候看到的文章并没有收藏,下次再找的时候十分不方便,这里做一个简单的小网页来提供知乎日报的搜索功能。

先放上网站链接:知乎日报搜索

前端样式比较丑,后期有时间进行改进。

一 抓取知乎日报内容

网上之前有调用http://zhihudaily.ahorn.me这个接口来返回知乎日报文章url,后来发现接口已经不可用,经过查找,发现可用的三个接口,还比较方便:

http://news-at.zhihu.com/api/3/news/latest  #获取最新消息

http://news.at.zhihu.com/api/3/news/before/20170401  #获取以前的消息,before后面要加日期

http://news-at.zhihu.com/api/3/news/  #获取指定消息,news后面加消息ID

后面的事情就好说了,随便写个爬虫,从2013年开始,抓到目前为止的所有内容,这里返回的都是json数据,更好处理。

二 使用sphinx作为中文搜索引擎

Sphinx的安装和使用

如果建立索引的时候报错,可以用一下参数:

/usr/local/sphinx-for-chinese/bin/indexer –all –rotate

三 搭建一个php代理处理图片盗链

把图片url抓取之后,发现知乎做了反盗链,图片没法直接显示,最后搭了简单的php代理,通过后端get_file_contents($image_url),或者通过curl设置referer, 请求原始图片数据echo 出来返回前端,这样就解决了知乎的反盗链。但是服务器需要下载和展示图片,流量会是原来的2倍,对于预算不足的服务器可能不太值当。另外可以把图片下载后放到微博的图床上,获取微博的未防盗链的图片,这样对服务器的性能会更好!


//防止别人用我的接口,这里判断refer,只有自己网站可用
if(isset($_SERVER['HTTP_REFERER']) &amp;amp;&amp;amp; (strpos($_SERVER['HTTP_REFERER'], 'http://zhihu.dadaaierer.com/') !== 0)) {
return;
}
if(!isset($_GET['url']) ||empty($_GET['url'])) {
return;
}
echo file_get_contents($_GET['url']);

文章中的img url通过


preg_replace('/src=\&amp;quot;(.*)\&amp;quot;/', 'src=&amp;quot;http://zhihu.dadaaierer.com/site/url?url=$1&amp;quot;', $tmp['content']);

替换,即可展示文章的图片。

957892883d1c4b6e7f469c69c4b2af6e

如图,搜索今日知乎日报小姐姐之后的结果。

PS:由于博主是单核1G阿里云服务器,图片请求全部打到php做的代理上已经出现扛不住,链接超时报502的错误,博主已经修改了php-fpm的默认max_children,希望近期能扛得住。

PHP正则表达式匹配嵌套HTML标签的方法和技巧

正则表达式是一个非常有用的编程技能。一般来说,简单的抓取一个HTML页面的某一条信息,比如<title>标题</title>,是很容易实现的。但是,我们往往要抓取某一个列表页面里的多个重复的<div></div>块里的特定内容,并且<div></div>块还有嵌套的使用,我们抓取的则是每个重复<div></div>块里的多个信息。同时,网页源文件不同于一般的字符串,其还存在大量的回车、换行和制表符,这些都造成了匹配失败。而初学者往往无法判断到底是哪个环节出现了问题,并且看到高度技巧化的正则表达式会感到非常沮丧,从而导致放弃问题的解决。

经过笔者多日的研究,终于摸索出以下方法和技巧,欢迎大家交流指正。

请看如下注意点和步骤:

1.注意/一定要被转义成\/,否则会报错

preg_match_all() [function.preg-match-all]: Unknown modifier

2.正则表达式用单引号’和/作为开始和结束的标界,比如’/reg partten/’,采用这样的写法,正则表达式里的双引号”不必转义

比如,

$partten=’/<div class=”goods_item”><a href=”([^<>]+)” target=”_blank”><img data-ks-lazyload=”([^<>]+)” alt=”([^<>]+)” width=”” height=””\/>/’;

3.需要先去除所有的换行符、制表符、回车等等,对于便于阅读的html源文件由于上述符号的存在会造成无法匹配。

$str=preg_replace(“/[\t\n\r]+/”,””,$str);

4.我们感兴趣的匹配信息,通常是html元素中的属性的值,因此要去除<>,否则只会匹配最后一条之前的全部信息。

比如,对于$string=”<div><a href=“1.jpg”></a></div><div><a href=“2.jpg”></a></div><div><a href=“3.jpg”></a></div>”,

$partten=’/<div><a href=“(.+)”/’;的匹配结果是:1.jpg”></a></div><div><a href=“2.jpg”></a></div><div><a href=“3.jpg”></a></div>

这是因为,上述给出的正则表达式确实没有限定匹配的范围只是第一个超链接<a href=“1.jpg”></a>。

因此,要想匹配上述三个超链接的 href属性,需要将上述匹配限定在<a href=“1.jpg”>里面,方法也很简单,将(.+)换成([^<>]+),即可。也就是说,这个匹配不包含下一个出现<>的地方,从而将匹配限定在同一个html标签内

做到以上几点,就可以完全无视html标签嵌套不嵌套的问题,从而抓取到一个页面所有的div重复块中我们感兴趣的内容,下附一例。


$html = $this->_query($url);
$html=preg_replace("/[\t\n\r]+/","",$html);
preg_match_all('/<h3>([^<>]+)<\/h3>/is', $html, $match);
var_dump($match);