使用Python解析网站

hah*_*aha 1 python regex

所以我设法将页面源作为字符串,但我的问题是,现在我需要解析它,例如.找到单词的每个实例并将下几行保存在数组中.

我看到的文字看起来像这样

<div class="searchResult">
        <table id="ctl00_lp_ctl01_lst" class="searchResultList" cellspacing="0" border="0" style="border-collapse:collapse;">
        <tr>
            <td class="searchResultI">
                <div class="date">
                    13:07
                    &nbsp;&nbsp;
                    17 July
                    </div>
                <div class="sTitle">
                    <a href="www.example1.com/result1">
                        Link Description</a></div>
                <div class="sSubTitle">
                    </div>
            </td>
        </tr><tr>
            <td class="searchResultAI">
                <div class="date">
                    20:07
                    &nbsp;&nbsp;
                    16 July
                    </div>
                <div class="sTitle">
                    <a href="www.example2.com/result2">
                        Link Description<</a></div>
                <div class="sSubTitle">
                    </div>
            </td>
        </tr><tr>

        and so on
Run Code Online (Sandbox Code Playgroud)

我想得到href链接和链接描述并将它们放在一个数组中.我不知道为什么这对我来说是如此微不足道,因为我用其他语言做了几个解析项目.我已经在网上搜索但没有任何帮助.

sgp*_*sgp 9

您不应该使用正则表达式来解析HTML.Python附带了许多用于HTML解析的解析器.这里的一个很好的选择是美丽的汤.这是让href链接使用汤的容易程度.

import urllib2
from bs4 import BeautifulSoup
url = urllib2.urlopen("http://www.example.com/").read()
soup = BeautifulSoup(url)
for line in soup.find_all('a'):
        print(line.get('href'))
Run Code Online (Sandbox Code Playgroud)