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

yipeiwu_com6年前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爬虫天气预报实例详解(小白入门)

Python爬虫天气预报实例详解(小白入门)

本文研究的主要是Python爬虫天气预报的相关内容,具体介绍如下。 这次要爬的站点是这个:http://www.weather.com.cn/forecast/ 要求是把你所在城市过去...

Python使用爬虫爬取静态网页图片的方法详解

Python使用爬虫爬取静态网页图片的方法详解

本文实例讲述了Python使用爬虫爬取静态网页图片的方法。分享给大家供大家参考,具体如下: 爬虫理论基础 其实爬虫没有大家想象的那么复杂,有时候也就是几行代码的事儿,千万不要把自己吓倒了...

Python使用Selenium+BeautifulSoup爬取淘宝搜索页

使用Selenium驱动chrome页面,获得淘宝信息并用BeautifulSoup分析得到结果。 使用Selenium时注意页面的加载判断,以及加载超时的异常处理。 impor...

Python爬取qq空间说说的实例代码

具体代码如下所示: #coding:utf-8 #!/usr/bin/python3 from selenium import webdriver import time impo...

python爬虫之爬取百度音乐的实现方法

python爬虫之爬取百度音乐的实现方法

在上次的爬虫中,抓取的数据主要用到的是第三方的Beautifulsoup库,然后对每一个具体的数据在网页中的selecter来找到它,每一个类别便有一个select方法。对网页有过接触的...