如何在Python中使用urllib2从打开的URL中提取特定数据?

3 投票
2 回答
3631 浏览
提问于 2025-04-15 12:13

我刚开始学习Python,正在尝试制作一个非常简单的网页爬虫。比如,我写了一个简单的函数,可以加载一个显示在线游戏高分的页面。这样,我就能获取到这个网页的源代码,但我需要从中提取出特定的数字。比如,这个网页的链接是这样的:

http://hiscore.runescape.com/hiscorepersonal.ws?user1=bigdrizzle13

其中,'bigdrizzle13'是链接中独特的部分。我想从这个页面中提取出数字并返回。简单来说,我想做一个程序,只需输入'bigdrizzle13',它就能输出这些数字。

2 个回答

3

你可以使用Beautiful Soup来解析HTML代码。

11

正如其他人提到的,BeautifulSoup 是一个非常棒的工具,适合这个工作。

下面是整个程序,里面有很多注释。虽然它可以更好地处理错误,但只要你输入一个有效的用户名,它就能从对应的网页上提取所有的分数。

我尽量写了详细的注释。如果你对BeautifulSoup还不太熟悉,我强烈建议你在使用我的例子时,手边准备好BeautifulSoup的文档

整个程序...

from urllib2 import urlopen
from BeautifulSoup import BeautifulSoup
import sys

URL = "http://hiscore.runescape.com/hiscorepersonal.ws?user1=" + sys.argv[1]

# Grab page html, create BeatifulSoup object
html = urlopen(URL).read()
soup = BeautifulSoup(html)

# Grab the <table id="mini_player"> element
scores = soup.find('table', {'id':'mini_player'})

# Get a list of all the <tr>s in the table, skip the header row
rows = scores.findAll('tr')[1:]

# Helper function to return concatenation of all character data in an element
def parse_string(el):
   text = ''.join(el.findAll(text=True))
   return text.strip()

for row in rows:

   # Get all the text from the <td>s
   data = map(parse_string, row.findAll('td'))

   # Skip the first td, which is an image
   data = data[1:]

   # Do something with the data...
   print data

这是一个测试运行的结果。

> test.py bigdrizzle13
[u'Overall', u'87,417', u'1,784', u'78,772,017']
[u'Attack', u'140,903', u'88', u'4,509,031']
[u'Defence', u'123,057', u'85', u'3,449,751']
[u'Strength', u'325,883', u'84', u'3,057,628']
[u'Hitpoints', u'245,982', u'85', u'3,571,420']
[u'Ranged', u'583,645', u'71', u'856,428']
[u'Prayer', u'227,853', u'62', u'357,847']
[u'Magic', u'368,201', u'75', u'1,264,042']
[u'Cooking', u'34,754', u'99', u'13,192,745']
[u'Woodcutting', u'50,080', u'93', u'7,751,265']
[u'Fletching', u'53,269', u'99', u'13,051,939']
[u'Fishing', u'5,195', u'99', u'14,512,569']
[u'Firemaking', u'46,398', u'88', u'4,677,933']
[u'Crafting', u'328,268', u'62', u'343,143']
[u'Smithing', u'39,898', u'77', u'1,561,493']
[u'Mining', u'31,584', u'85', u'3,331,051']
[u'Herblore', u'247,149', u'52', u'135,215']
[u'Agility', u'225,869', u'60', u'276,753']
[u'Thieving', u'292,638', u'56', u'193,037']
[u'Slayer', u'113,245', u'73', u'998,607']
[u'Farming', u'204,608', u'51', u'115,507']
[u'Runecraft', u'38,369', u'71', u'880,789']
[u'Hunter', u'384,920', u'53', u'139,030']
[u'Construction', u'232,379', u'52', u'125,708']
[u'Summoning', u'87,236', u'64', u'419,086']

好了 :)

撰写回答