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程序设计的学习有所帮助。
相关文章
Pandas读取excel合并单元格的正确方式(openpyxl合并单元格拆分并填充内容)
Excel文件中可能包含合并单元格的数据,下面这篇文章主要给大家介绍了关于Pandas读取excel合并单元格的正确方式,主要介绍的openpyxl合并单元格拆分并填充内容,需要的朋友可以参考下2023-06-06Python中json.dumps()和json.dump()的区别小结
在Python中,json.dumps()和json.dump()是两个常用的函数,本文主要介绍了Python中json.dumps()和json.dump()的区别小结,具有一定的参考价值,感兴趣的可以了解一下2024-02-02python使用PIL和matplotlib获取图片像素点并合并解析
这篇文章主要介绍了python使用PIL和matplotlib获取图片像素点并合并解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2019-09-09
最新评论