php多线程抓取多个网页(GoogleWebSearchAPI+多线程文档中给出使用Python进行搜索)
优采云 发布时间: 2022-01-05 13:11php多线程抓取多个网页(GoogleWebSearchAPI+多线程文档中给出使用Python进行搜索)
1)urllib2+BeautifulSoup 抓取Goolge 搜索链接
最近参与项目需要处理谷歌搜索结果,之前学习过网页处理相关的Python工具。在实际应用中,urllib2和beautifulsoup是用来抓取网页的,但是在抓取谷歌搜索结果的时候,发现如果直接处理谷歌搜索结果页面的源码,会得到很多“脏”的链接。
看下图搜索“titanic james”的结果:
图中红色标注的不需要,蓝色标注的需要抓取处理。
这种“脏链接”当然可以通过常规过滤的方式过滤掉,但是程序的复杂度很高。就在我一脸悲伤地写过滤规则的时候。同学提醒谷歌应该提供相关的API,突然就明白了。
(2)Google 网页搜索 API+多线程
文档中给出了使用 Python 进行搜索的示例:
图中红色标注的不需要,蓝色标注的需要抓取处理。
这种“脏链接”当然可以通过常规过滤的方式过滤掉,但是程序的复杂度很高。就在我一脸悲伤地写过滤规则的时候。同学提醒谷歌应该提供相关的API,突然就明白了。
(2)Google 网页搜索 API+多线程
文档中给出了使用 Python 进行搜索的示例:
在实际应用中,可能需要抓取Google的很多网页,因此需要使用多线程来分担抓取任务。使用google web search api的详细介绍请看这里(这里介绍了Standard URL Arguments)。另外要特别注意的是url中的参数rsz必须是8(包括8)以下的值。如果大于8会报错!
(3)代码实现
代码实现还是有问题,但是可以运行,健壮性差,有待改进。希望各位大神指出错误(初学者Python),万分感谢。
#-*-coding:utf-8-*-
import urllib2,urllib
import simplejson
import os, time,threading
import common, html_filter
#input the keywords
keywords = raw_input('Enter the keywords: ')
#define rnum_perpage, pages
rnum_perpage=8
pages=8
#定义线程函数
def thread_scratch(url, rnum_perpage, page):
url_set = []
try:
request = urllib2.Request(url, None, {'Referer': 'http://www.sina.com'})
response = urllib2.urlopen(request)
# Process the JSON string.
results = simplejson.load(response)
info = results['responseData']['results']
except Exception,e:
print 'error occured'
print e
else:
for minfo in info:
url_set.append(minfo['url'])
print minfo['url']
#处理链接
i = 0
for u in url_set:
try:
request_url = urllib2.Request(u, None, {'Referer': 'http://www.sina.com'})
request_url.add_header(
'User-agent',
'CSC'
)
response_data = urllib2.urlopen(request_url).read()
#过滤文件
#content_data = html_filter.filter_tags(response_data)
#写入文件
filenum = i+page
filename = dir_name+'/related_html_'+str(filenum)
print ' write start: related_html_'+str(filenum)
f = open(filename, 'w+', -1)
f.write(response_data)
#print content_data
f.close()
print ' write down: related_html_'+str(filenum)
except Exception, e:
print 'error occured 2'
print e
i = i+1
return
#创建文件夹
dir_name = 'related_html_'+urllib.quote(keywords)
if os.path.exists(dir_name):
print 'exists file'
common.delete_dir_or_file(dir_name)
os.makedirs(dir_name)
#抓取网页
print 'start to scratch web pages:'
for x in range(pages):
print "page:%s"%(x+1)
page = x * rnum_perpage
url = ('https://ajax.googleapis.com/ajax/services/search/web'
'?v=1.0&q=%s&rsz=%s&start=%s') % (urllib.quote(keywords), rnum_perpage,page)
print url
t = threading.Thread(target=thread_scratch, args=(url,rnum_perpage, page))
t.start()
#主线程等待子线程抓取完
main_thread = threading.currentThread()
for t in threading.enumerate():
if t is main_thread:
continue
t.join()
免责声明:本文原创发表于php中文网。转载请注明出处。感谢您的尊重!如果您有任何疑问,请与我们联系
推荐主题:
上一篇:Python 多线程编程 3:使用互斥锁同步线程 下一篇:在 Go 中编写 CPython 来扩展 goPy