Python多线程抓取Google搜索链接网页

1)urllib2+beautifulsoup抓取goolge搜索链接

近期,参与的项目需要对Google搜索结果进行处理,之前学习了Python处理网页相关的工具。实际应用中,使用了urllib2和beautifulsoup来进行网页的抓取,但是在抓取google搜索结果的时候,发现如果是直接对google搜索结果页面的源代码进行处理,会得到很多“脏”链接。

看下图为搜索“titanic  james”的结果:

1.jpg

图中红色标记的是不需要的,蓝色标记的是需要抓取处理的。

立即学习“Python免费学习笔记(深入)”;

这种“脏链接”当然可以通过规则过滤的方法来过滤掉,但是这样程序的复杂度就高了。正当自己愁眉苦脸的正在写过滤规则时。同学提醒说google应该提供相关的api,才恍然大明白。

(2)Google Web Search API+多线程

文档中给出使用Python进行搜索的例子:

图中红色标记的是不需要的,蓝色标记的是需要抓取处理的。

立即学习“Python免费学习笔记(深入)”;

这种“脏链接”当然可以通过规则过滤的方法来过滤掉,但是这样程序的复杂度就高了。正当自己愁眉苦脸的正在写过滤规则时。同学提醒说google应该提供相关的api,才恍然大明白。

(2)Google Web Search API+多线程

文档中给出使用Python进行搜索的例子:

import simplejson    # The request also includes the userip parameter which provides the end # user's IP address. Doing so will help distinguish this legitimate # server-side traffic from traffic which doesn't come from an end-user. url = ('https://ajax.googleapis.com/ajax/services/search/web'       '?v=1.0&q=Paris%20Hilton&userip=USERS-IP-ADDRESS')    request = urllib2.Request(    url, None, {'Referer': /* Enter the URL of your site here */})response = urllib2.urlopen(request)    # Process the JSON string. results = simplejson.load(response)# now have some fun with the results...  import simplejson   # The request also includes the userip parameter which provides the end# user's IP address. Doing so will help distinguish this legitimate# server-side traffic from traffic which doesn't come from an end-user.url = ('https://ajax.googleapis.com/ajax/services/search/web'       '?v=1.0&q=Paris%20Hilton&userip=USERS-IP-ADDRESS')   request = urllib2.Request(    url, None, {'Referer': /* Enter the URL of your site here */})response = urllib2.urlopen(request)   # Process the JSON string.results = simplejson.load(response)# now have some fun with the results..

登录后复制

实际应用中可能需要抓取google的很多网页,所以还需要使用多线程来分担抓取任务。使用google web search api的参考详细介绍,请看此处(这里介绍了Standard URL Arguments)。另外要特别注意,url中参数rsz必须是8(包括8)以下的值,若大于8,会报错的!

(3)代码实现

代码实现还存在问题,但是能够运行,鲁棒性差,还需要进行改进,希望各路大神指出错误(初学Python),不胜感激。

#-*-coding:utf-8-*- import urllib2,urllibimport simplejsonimport os, time,threading   import common, html_filter#input the keywords keywords = raw_input('Enter the keywords: ')                                    #define rnum_perpage, pages rnum_perpage=8pages=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()

登录后复制

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2284489.html

(0)
上一篇 2025年2月27日 20:45:27
下一篇 2025年2月26日 23:12:04

AD推荐 黄金广告位招租... 更多推荐

相关推荐

  • python多线程编程2

    如上一节,python的threading.thread类有一个run方法,用于定义线程的功能函数,可以在自己的线程类中覆盖该方法。而创建自己的线程实例后,通过thread类的start方法,可以启动该线程,交给python虚拟机进行调度,…

    编程技术 2025年2月27日
    200
  • python多线程编程1

    多线程编程必须理解的一些基本概念,适用于所有编程语言。内容: 并发式编程 多任务操作系统 多线程vs多进程 线程安全 立即学习“Python免费学习笔记(深入)”; 线程的生命周期 线程的类型 并发式编程 不同的编程范式对软件有不同的视角。…

    编程技术 2025年2月27日
    200
  • 使用Python读取和写入mp3文件的id3v1信息

    1.起因 一直以来疯迷“冬吴相对论”,为了整理下载他的MP3花了不少功夫,今天突然发现将电脑中的mp3导入到itunes后,文件名竟然不识别了。#_* itunes自动识别了mp3的信息内容。多次一举么,文件名挺好。事实如此,让我深感不完美…

    编程技术 2025年2月27日
    200
  • Python连接Redis连接配置

    系统环境: OS:Oracle Linux Enterprise 5.6 redis:redis-2.6.8 python:Python-2.7.3 redis的python包版本:redis-2.7.2.tar 立即学习“Python免费…

    编程技术 2025年2月27日
    200
  • Python 支持重启的异步 IO

    摘要 这是一份从Python3.3开始的Python3异步I/O提议。研究从PEP 3153缺失的具体提议。 这提议包括了一个可插入式的事件循环API,传输和与Twisted相似的协议抽象,以及来自(PEP 380) 基于yield的更高级…

    编程技术 2025年2月27日
    200
  • python发送邮件实例 – 使用smtplib模块

    # 导入 smtplib 和 MIMETextimport smtplibfrom email.mime.text import MIMEText    # 定义发送列表mailto_list=[“root@pythontab.com”,”…

    编程技术 2025年2月27日
    200
  • 用Python备份MYSQL 数据库

    工作需要,对公司的mysql数据库进行备份,赶上刚刚开始学python,看了一套简单的python教学视频,简单的写了个备份脚本,个人表示 对python 的class 、function、build-in function 、私有变量、全…

    编程技术 2025年2月27日
    200
  • python读取和生成excel文件

    今天来看一下如何使用python处理excel文件,处理excel文件是在工作中经常用到的,python为我们考虑到了这一点,python中本身就自带csv模块。 1.用python读取csv文件: csv是逗号分隔符格式 一般我们用的ex…

    2025年2月27日
    100
  • 用python脚本监控并发量

    该脚本作用用于查询日志过去一分钟内的并发量,并发单位位1分钟,结果打印在标准输出中,可以配合一些软件实现日志的并发实时监控,比如zabbix。 #! /usr/local/bin/python3import sysimport reimpo…

    编程技术 2025年2月27日
    200
  • 用50行Python代码制作一个计算器

    简介 在这篇文章中,我将向大家演示怎样向一个通用计算器一样解析并计算一个四则运算表达式。当我们结束的时候,我们将得到一个可以处理诸如 1+2*-(-3+2)/5.6+3样式的表达式的计算器了。当然,你也可以将它拓展的更为强大。 我本意是想提…

    编程技术 2025年2月27日
    200

发表回复

登录后才能评论