本文以实例形式讲述了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怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
C++高性能并发应用_C++如何开发性能关键应用
Java AI集成Deep Java Library_Java怎么集成AI模型部署
Golang后端API开发_Golang如何高效开发后端和API
Python异步并发改进_Python异步编程有哪些新改进
C++系统编程内存管理_C++系统编程怎么与Rust竞争内存安全
Java GraalVM原生镜像构建_Java怎么用GraalVM构建高效原生镜像
Python FastAPI异步API开发_Python怎么用FastAPI构建异步API
C++现代C++20/23/26特性_现代C++有哪些新标准特性如modules和coroutines
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号