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爬虫爬取煎蛋网图片代码实例

这篇文章主要介绍了Python爬虫爬取煎蛋网图片代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下今天,试着爬取了煎蛋网的图片。用到...

Python HTML解析模块HTMLParser用法分析【爬虫工具】

本文实例讲述了Python HTML解析模块HTMLParser用法。分享给大家供大家参考,具体如下: 简介 先简略介绍一下。实际上,HTMLParser是python用来解析HTML的...

python抓取京东商城手机列表url实例代码

复制代码 代码如下:#-*- coding: UTF-8 -*-'''Created on 2013-12-5 @author: good-temper''' import urllib...

Python爬虫通过替换http request header来欺骗浏览器实现登录功能

Python爬虫通过替换http request header来欺骗浏览器实现登录功能

以豆瓣为例,访问https://www.douban.com/contacts/list 来查看自己关注的人,要登录才能查看。 如果用requests.get()方法获取这个http,没...

python按综合、销量排序抓取100页的淘宝商品列表信息

进入淘宝网,分别按综合、销量排序抓取100页的所有商品的列表信息。 1、按综合 import re from selenium import webdriver from s...