抓取html数据并解析成lis

2024-09-28 21:26:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用pythonforandroid(sl4a)编写一个android应用程序,我想让它搜索一个笑话网站并提取一个笑话。那就告诉我那个笑话好让我清醒过来。到目前为止,它将原始的html源文件保存到一个列表中,但是我需要它来创建一个新的列表,方法是在html标记之间保存数据,然后将这些数据读给我。我无法使用解析器。代码如下:

import android
droid = android.Android() 
import urllib 
current = 0
newlist = []

sock = urllib.urlopen("http://m.funtweets.com/random") 
htmlSource = sock.read() 
sock.close() 
rawhtml = []
rawhtml.append (htmlSource)

while current < len(rawhtml):
    while current != "<div class=":
        if [current] == "</b></a>":
            newlist.append (current)
            current += 1


print newlist

Tags: 数据import列表htmlcurrenturllib笑话android
2条回答

方法如下: [代码] 进口re 导入urllib2

page = urllib2.urlopen("http://www.m.funtweets.com/random").read() 
user = re.compile(r'<span>@</span>(\w+)') 
text = re.compile(r"</b></a> (\w.*)") 
user_lst =[match.group(1) for match in re.finditer(user, page)] 
text_lst =[match.group(1) for match in re.finditer(text, page)] 
for _user, _text in zip(user_lst, text_lst):
    print '@{0}\n{1}\n'.format(_user,_text)

[/代码]

在android中使用这个LIB来解析HTMLhttp://jsoup.org/它的范围和开发人员广泛接受的LIB它也可以用于python:)

相关问题 更多 >