惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
Engineering at Meta
Engineering at Meta
A
About on SuperTechFans
T
The Blog of Author Tim Ferriss
I
InfoQ
博客园_首页
G
Google Developers Blog
爱范儿
爱范儿
Last Week in AI
Last Week in AI
量子位
阮一峰的网络日志
阮一峰的网络日志
雷峰网
雷峰网
酷 壳 – CoolShell
酷 壳 – CoolShell
Vercel News
Vercel News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
GbyAI
GbyAI
月光博客
月光博客
The GitHub Blog
The GitHub Blog
V
Visual Studio Blog
N
Netflix TechBlog - Medium
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 司徒正美
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东

博客园 - shaoyun

多线程采集器的核心代码 ThinkPHP2.1模版使用笔记 - 模版嵌套/AJAX级联 畅想无线显示技术 ASP.Net 一步一步学习分页(适合初学者) - shaoyun - 博客园 OAuth协议分析一 通用四级联动下拉列表 通用手动分页方法 通用三级联动下拉列表 Indy 邮件发送的例子 Indy 组件学习注意事项 利用API的消息发送程序原理 Delphi DLL 的编写 Discuz!NT3.1 子目录安装实例 Delphi 托盘程序示例 Delphi ADO 学习笔记 SQL获取数据表的空间占用 C#编写简单的系统服务管理器 很久没有写博了,发发挠骚 Twitter被封后教你继续访问的方法
Python抓取百度搜索结果
shaoyun · 2012-08-21 · via 博客园 - shaoyun

Python 用来做一些简单的工作还是不错的,一个练手的代码,抓取百度关键字搜索的结果

# coding=utf-8
import urllib2 as url
import string
import urllib
import re

def baidu_search(keyword):
    p= {'wd': keyword}
    res=url.urlopen("http://www.baidu.com/s?"+urllib.urlencode(p))
    html=res.read()
    return html
def getList(regex,text):
    arr = []
    res = re.findall(regex, text)
    if res:
        for r in res:
            arr.append(r)
    return arr
def getMatch(regex,text):
    res = re.findall(regex, text)
    if res:
        return res[0]
    return ""
def clearTag(text):
    p = re.compile(u'<[^>]+>')
    retval = p.sub("",text)
    return retval

html = baidu_search('天下无贼')
content = unicode(html, 'utf-8','ignore')

arrList = getList(u"<table.*?class=\"result\".*?>.*?<\/a>", content)
for item in arrList:
    regex = u"<h3.*?class=\"t\".*?><a.*?href=\"(.*?)\".*?>(.*?)<\/a>"
    link = getMatch(regex,item)
    url = link[0]
    title = clearTag(link[1]).encode('utf8')
    print url
    print title