源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python实现抓取网页并且解析的实例

  • 时间:2022-11-21 20:51 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要: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 + "twendat0";
    else:
      print query + "twendat1";
  else:
    print query + "twendat0";
  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 + "tbaidut1";
  else:
    print query + "tbaidut0";
  maxline = maxline - 1;
f1.close()
f2.close()

希望本文所述对大家Python程序设计的学习有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部