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使用自定义user-agent抓取网页的方法

本文实例讲述了python使用自定义user-agent抓取网页的方法。分享给大家供大家参考。具体如下: 下面python代码通过urllib2抓取指定的url的内容,并且使用自定义的u...

python urllib爬取百度云连接的实例代码

python urllib爬取百度云连接的实例代码

翻看自己以前写的程序,发现写过一个爬取盘多多百度云资源的东西,完全是当时想看变形金刚才自己写的,而且当时第一次接触python大概写了有2天才搞出来这个程序,学习python语言,可以看...

python 实现一个贴吧图片爬虫的示例

python 实现一个贴吧图片爬虫的示例

今天没事回家写了个贴吧图片下载程序,工具用的是PyCharm,这个工具很实用,开始用的Eclipse,但是再使用类库或者其它方便并不实用,所以最后下了个专业开发python程序的工具,开...

Python爬虫:通过关键字爬取百度图片

Python爬虫:通过关键字爬取百度图片

使用工具:Python2.7 点我下载 scrapy框架 sublime text3 一。搭建python(Windows版本)  1.安装python2.7 ---然后在cm...

Python实现的文轩网爬虫完整示例

本文实例讲述了Python实现的文轩网爬虫。分享给大家供大家参考,具体如下: encoding=utf8 import pymysql import time import sys...