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程序设计的学习有所帮助。

相关文章

Python3直接爬取图片URL并保存示例

有时候我们会需要从网络上爬取一些图片,来满足我们形形色色直至不可描述的需求。 一个典型的简单爬虫项目步骤包括两步:获取网页地址和提取保存数据。 这里是一个简单的从图片url收集图片的例子...

Python爬虫爬取新浪微博内容示例【基于代理IP】

Python爬虫爬取新浪微博内容示例【基于代理IP】

本文实例讲述了Python爬虫爬取新浪微博内容。分享给大家供大家参考,具体如下: 用Python编写爬虫,爬取微博大V的微博内容,本文以女神的微博为例(爬新浪m站:https://m.w...

Python爬虫之正则表达式基本用法实例分析

Python爬虫之正则表达式基本用法实例分析

本文实例讲述了Python爬虫之正则表达式基本用法。分享给大家供大家参考,具体如下: 一、简介 正则表达式,又称正规表示式、正规表示法、正规表达式、规则表达式、常规表示法(英语:Regu...

python爬虫简单的添加代理进行访问的实现代码

python爬虫简单的添加代理进行访问的实现代码

在使用python对网页进行多次快速爬取的时候,访问次数过于频繁,服务器不会考虑User-Agent的信息,会直接把你视为爬虫,从而过滤掉,拒绝你的访问,在这种时候就需要设置代理,我们可...

Python urllib、urllib2、httplib抓取网页代码实例

使用urllib2,太强大了 试了下用代理登陆拉取cookie,跳转抓图片...... 文档:http://docs.python.org/library/urllib2.html 直接...