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爬取指定微信公众号文章

本文实例为大家分享了python爬取微信公众号文章的具体代码,供大家参考,具体内容如下 该方法是依赖于urllib2库来完成的,首先你需要安装好你的python环境,然后安装urllib...

Python抓取聚划算商品分析页面获取商品信息并以XML格式保存到本地

本文实例为大家分享了Python抓取聚划算商品页面获取商品信息并保存的具体代码,供大家参考,具体内容如下 #!/user/bin/python # -*- coding: gbk...

python requests抓取one推送文字和图片代码实例

这篇文章主要介绍了python requests抓取one推送文字和图片代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 req...

玩转python爬虫之cookie使用方法

玩转python爬虫之cookie使用方法

之前一篇文章我们学习了爬虫的异常处理问题,那么接下来我们一起来看一下Cookie的使用。 为什么要使用Cookie呢? Cookie,指某些网站为了辨别用户身份、进行session跟踪而...

python使用rabbitmq实现网络爬虫示例

编写tasks.py复制代码 代码如下:from celery import Celeryfrom tornado.httpclient import HTTPClientapp = C...