Python regex查找多行HTML

2024-10-03 13:29:30 发布

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

如何在Python中使用regex解析HTML中的多行。我已经设法使用下面的代码在同一行上串匹配模式。你知道吗

i=0
while i<len(newschoollist):
    url = "http://profiles.doe.mass.edu/profiles/general.aspx?topNavId=1&orgcode="+ newschoollist[i] +"&orgtypecode=6&"
    htmlfile = urllib.urlopen(url)
    htmltext = htmlfile.read()
    regex = '>Phone:</td><td>(.+?)</td></tr>'
    pattern = re.compile(regex)
    value = re.findall(pattern,htmltext)
    print newschoollist[i], valuetag, value
    i+=1

然而,当我试图识别像这样更复杂的HTML时。。。你知道吗

<td>Attendance Rate</td> 
<td class='center'>  90.1</td>  

我得到空值。我相信问题出在我的语法上。我已经在google上搜索过regex并阅读了大部分文档,但是我正在寻找这种应用程序的帮助。我希望有人能给我指出正确的方向。是否有(+?)像这样的组合可以帮助我告诉regex跳过一行HTML?你知道吗

我希望findall找到的是90.1 “出勤率 ““

谢谢!你知道吗


Tags: 代码reurlvaluehtmlprofilesregextd
2条回答

最后我用了(soup.get\u文本())效果很好。谢谢!你知道吗

Use an HTML Parser。使用^{}的示例:

from urllib2 import urlopen
from bs4 import BeautifulSoup

url = 'http://profiles.doe.mass.edu/profiles/general.aspx?topNavId=1&orgcode=00350326'

soup = BeautifulSoup(urlopen(url))
for label in soup.select('div#whiteboxRight table td'):
    value = label.find_next_sibling('td')
    if not value:
        continue

    print label.get_text(strip=True), value.get_text(strip=True)
    print "  "

打印(个人资料联系信息):

...
  
NCES ID: 250279000331
  
Web Site: http://www.bostonpublicschools.org
  
MA School Type: Public School
  
NCES School Reconstituted: No
...

相关问题 更多 >