Python实现抓取网页并且解析的实例

yipeiwu_com5年前Python爬虫

本文以实例形式讲述了Python实现抓取网页并解析的功能。主要解析问答与百度的首页。分享给大家供大家参考之用。

主要功能代码如下:

#!/usr/bin/python
#coding=utf-8

import sys 
import re
import urllib2
from urllib import urlencode
from urllib import quote
import time
maxline = 2000

wenda = re.compile("href=\"http://wenda.so.com/q/.+\?src=(.+?)\"")
baidu = re.compile("<a href=\"http://www.baidu.com/link\?url=.+\".*?>更多知道相关问题.*?</a>")
f1 = open("baidupage.txt","w")
f2 = open("wendapage.txt","w")

for line in sys.stdin:
  if maxline == 0:
    break
  query = line.strip();
  time.sleep(1);
  recall_url = "http://www.so.com/s?&q=" + query;
  response = urllib2.urlopen(recall_url);
  html = response.read();                                                   
  f1.write(html)
  m = wenda.search(html);
  if m:
    if m.group(1) == "110":
      print query + "\twenda\t0";
    else:
      print query + "\twenda\t1";
  else:
    print query + "\twenda\t0";
  recall_url = "http://www.baidu.com/s?wd=" + query +"&ie=utf-8";
  response = urllib2.urlopen(recall_url);
  html = response.read();
  f2.write(html)
  m = baidu.search(html);
  if m:
    print query + "\tbaidu\t1";
  else:
    print query + "\tbaidu\t0";
  maxline = maxline - 1;
f1.close()
f2.close()

希望本文所述对大家Python程序设计的学习有所帮助。

相关文章

python实现爬虫统计学校BBS男女比例之多线程爬虫(二)

接着第一篇继续学习。 一、数据分类 正确数据:id、性别、活动时间三者都有 放在这个文件里file1 = 'ruisi\\correct%s-%s.txt' % (startNum, e...

python定向爬虫校园论坛帖子信息

引言 写这个小爬虫主要是为了爬校园论坛上的实习信息,主要采用了Requests库 源码 URLs.py 主要功能是根据一个初始url(包含page页面参数)来获得page页面从当前页面数...

Python3多线程爬虫实例讲解代码

多线程概述 多线程使得程序内部可以分出多个线程来做多件事情,充分利用CPU空闲时间,提升处理效率。python提供了两个模块来实现多线程thread 和threading ,thread...

Python tornado队列示例-一个并发web爬虫代码分享

Queue Tornado的tornado.queue模块为基于协程的应用程序实现了一个异步生产者/消费者模式的队列。这与python标准库为多线程环境实现的queue模块类似。 一个协...

Python爬虫实现使用beautifulSoup4爬取名言网功能案例

本文实例讲述了Python爬虫实现使用beautifulSoup4爬取名言网功能。分享给大家供大家参考,具体如下: 爬取名言网top10标签对应的名言,并存储到mysql中,字段(名言,...