Python實現抓取網頁并且解析的實例
更新時間:2014年09月20日 17:39:07 投稿:shichen2014
這篇文章主要介紹了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程序設計的學習有所幫助。

