5

从 URL 检索到的特定页面具有以下语法:

<p>
    <strong>Name:</strong> Pasan <br/>
    <strong>Surname: </strong> Wijesingher <br/>                    
    <strong>Former/AKA Name:</strong> No Former/AKA Name <br/>                    
    <strong>Gender:</strong> Male <br/>
    <strong>Language Fluency:</strong> ENGLISH <br/>                    
</p>

我想提取姓名、姓氏等中的数据。(我必须对许多页面重复此任务)

为此,我尝试使用以下代码:

import urllib2

url = 'http://www.my.lk/details.aspx?view=1&id=%2031'
source = urllib2.urlopen(url)

start = '<p><strong>Given Name:</strong>'
end = '<strong>Surname'
givenName=(source.read().split(start))[1].split(end)[0]

start = 'Surname: </strong>'
end = 'Former/AKA Name'
surname=(source.read().split(start))[1].split(end)[0]

print(givenName)
print(surname)

当我只调用一次 source.read.split 方法时,它工作正常。但是当我使用它两次时,它会给出一个列表索引超出范围错误。

有人可以提出解决方案吗?

4

4 回答 4

7

您可以使用BeautifulSoup来解析 HTML 字符串。

这是您可以尝试的一些代码,
它使用 BeautifulSoup(获取由 html 代码生成的文本),然后解析字符串以提取数据。

from bs4 import BeautifulSoup as bs

dic = {}
data = \
"""
    <p>
        <strong>Name:</strong> Pasan <br/>
        <strong>Surname: </strong> Wijesingher <br/>                    
        <strong>Former/AKA Name:</strong> No Former/AKA Name <br/>                    
        <strong>Gender:</strong> Male <br/>
        <strong>Language Fluency:</strong> ENGLISH <br/>                    
    </p>
"""

soup = bs(data)
# Get the text on the html through BeautifulSoup
text = soup.get_text()

# parsing the text
lines = text.splitlines()
for line in lines:
    # check if line has ':', if it doesn't, move to the next line
    if line.find(':') == -1: 
        continue    
    # split the string at ':'
    parts = line.split(':')

    # You can add more tests here like
    # if len(parts) != 2:
    #     continue

    # stripping whitespace
    for i in range(len(parts)):
        parts[i] = parts[i].strip()    
    # adding the vaules to a dictionary
    dic[parts[0]] = parts[1]
    # printing the data after processing
    print '%16s %20s' % (parts[0],parts[1])

提示:如果你打算使用 BeautifulSoup 来解析 HTML,
你应该有某些属性,比如class=inputor id=10,也就是说,你保持所有相同类型的标签是相同的 id 或类。


更新
您的评论,请参阅下面的代码
它应用了上面的提示,使生活(和编码)更容易

from bs4 import BeautifulSoup as bs

c_addr = []
id_addr = []
data = \
"""
<h2>Primary Location</h2>
<div class="address" id="10">
    <p>
       No. 4<br>
       Private Drive,<br>
       Sri Lanka&nbsp;ON&nbsp;&nbsp;K7L LK <br>
"""
soup = bs(data)

for i in soup.find_all('div'):
    # get data using "class" attribute
    addr = ""
    if i.get("class")[0] == u'address': # unicode string
        text = i.get_text()
        for line in text.splitlines(): # line-wise
            line = line.strip() # remove whitespace
            addr += line # add to address string
        c_addr.append(addr)

    # get data using "id" attribute
    addr = ""
    if int(i.get("id")) == 10: # integer
        text = i.get_text()
        # same processing as above
        for line in text.splitlines():
            line = line.strip()
            addr += line
        id_addr.append(addr)

print "id_addr"
print id_addr
print "c_addr"
print c_addr
于 2013-02-23T05:24:49.003 回答
5

您正在调用 read() 两次。那就是问题所在。您不想这样做,而是想调用一次 read,将数据存储在一个变量中,然后在调用 read() 的地方使用该变量。像这样的东西:

fetched_data = source.read()

然后后来...

givenName=(fetched_data.split(start))[1].split(end)[0]

和...

surname=(fetched_data.split(start))[1].split(end)[0]

那应该行得通。您的代码不起作用的原因是因为 read() 方法是第一次读取内容,但是在完成读取后,它正在查看内容的末尾。下次您调用 read() 时,它没有剩余内容并引发异常。

查看urllib2的文档和文件对象的方法

于 2013-02-23T05:31:16.873 回答
1

如果你想快点,正则表达式对这类任务更有用。一开始这可能是一个艰难的学习曲线,但正则表达式有一天会拯救你的屁股。

试试这个代码:

# read the whole document into memory
full_source = source.read()  

NAME_RE = re.compile('Name:.+?>(.*?)<')
SURNAME_RE = re.compile('Surname:.+?>(.*?)<')

name = NAME_RE.search(full_source, re.MULTILINE).group(1).strip()
surname = SURNAME_RE.search(full_source, re.MULTILINE).group(1).strip()

有关如何在 python 中使用正则表达式的更多信息,请参见此处。

更全面的解决方案将涉及解析 HTML(使用 BeautifulSoup 之类的库),但这可能会根据您的特定应用程序而过大。

于 2013-02-23T05:52:33.203 回答
1

您可以使用 HTQL:

page="""
<p>
    <strong>Name:</strong> Pasan <br/>
    <strong>Surname: </strong> Wijesingher <br/>                    
    <strong>Former/AKA Name:</strong> No Former/AKA Name <br/>                    
    <strong>Gender:</strong> Male <br/>
    <strong>Language Fluency:</strong> ENGLISH <br/>                    
</p>
"""

import htql
print(htql.query(page, "<p>.<strong> {a=:tx; b=:xx} "))

# [('Name:', ' Pasan '), 
#  ('Surname: ', ' Wijesingher '), 
#  ('Former/AKA Name:', ' No Former/AKA Name '), 
#  ('Gender:', ' Male '), 
#  ('Language Fluency:', ' ENGLISH ')
# ]
于 2013-02-26T04:58:17.017 回答