BeautifulSoup 善于网页HTML解析 ,抓取CSDN极客头条内容放入 ListView ,
用户点击选择,用 webViewShow 网页href
geek.py 超过100行,得闲时看吧
# -*- coding: utf-8 -*-
import android
import urllib2, re
from BeautifulSoup import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
droid = android.Android()
droid.addOptionsMenuItem('Exit','exit')
def getText(text):
begin = text.find('>',0)
if begin > -1:
begin += 1
end = text.find('</a>',begin)
if begin < end:
return text[begin:end].strip()
else:
return None
else:
return None
alist =[]
blist =[]
def getPage(url):
global alist,blist
if url is None or len(url)<10: return
alist =[]
blist =[]
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)
for h4 in soup.findAll('h4'):
if h4.a is not None:
href = h4.a.get('href')
text = getText(str(h4.a))
alist.append(href)
blist.append(text)
page.close()
droid.fullSetList("listView",blist)
return
def selectedItem(id):
global alist
href = alist[int(id)]
print href
droid.webViewShow(href)
def eventloop():
while True:
event=droid.eventWait().result
if event['name']=='exit':
return
if event["name"]=="itemclick":
id=event["data"]["position"]
if id:
selectedItem(id)
if event["name"]=="click":
id=event["data"]["id"]
if id=="Exit":
return
if id=="Hot":
getPage("http://geek.csdn.net/hot")
if id=="New":
getPage("http://geek.csdn.net/new")
elif event["name"]=="screen":
if event["data"]=="destroy":
return
layout = """<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/background"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:background="#ff000000">
<LinearLayout android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:focusable="true"
android:focusableInTouchMode="true">
<Button
android:id="@+id/Exit"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="Exit"
/>
<Button
android:id="@+id/Hot"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="geek最热"
/>
<Button
android:id="@+id/New"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="geek最新"
/>
</LinearLayout>
<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FF0400"
android:background="#004000"
android:padding="5dip"
/>
</LinearLayout>
"""
droid.fullShow(layout)
eventloop()
droid.fullDismiss()