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利用selenium进行浏览器爬虫

python利用selenium进行浏览器爬虫

前言 相信大家刚开始在做爬虫的时候,是不是requests和sound这两个库来使用,这样确实有助于我们学习爬虫的知识点,下面来介绍一个算事较复杂的爬虫案例selenium进形打开浏览器...

Python实现爬取百度贴吧帖子所有楼层图片的爬虫示例

Python实现爬取百度贴吧帖子所有楼层图片的爬虫示例

本文实例讲述了Python实现爬取百度贴吧帖子所有楼层图片的爬虫。分享给大家供大家参考,具体如下: 下载百度贴吧帖子图片,好好看 python2.7版本: #coding=utf-...

Python3爬虫之urllib携带cookie爬取网页的方法

如下所示: import urllib.request import urllib.parse url = 'https://weibo.cn/5273088553/info'...

python爬取51job中hr的邮箱

本文实例为大家分享了python爬取51job中hr的邮箱具体代码,供大家参考,具体内容如下 #encoding=utf8 import urllib2 import cookie...

一个月入门Python爬虫学习,轻松爬取大规模数据

一个月入门Python爬虫学习,轻松爬取大规模数据

Python爬虫为什么受欢迎 如果你仔细观察,就不难发现,懂爬虫、学习爬虫的人越来越多,一方面,互联网可以获取的数据越来越多,另一方面,像 Python这样的编程语言提供越来越多的优秀工...