用python regex抓取html

2024-06-16 08:47:47 发布

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

我对python中的regex有一些问题。我有一些html页面,其中包含对我有用的信息。在保存页面时,encodig字符集是一种iso。。。 它保存了所有德国典型的字母编码,例如“Fr%C3%BCchte”为Früchte和son on。 html的结构非常糟糕,因此唯一合理的方法就是使用regex。在

我在python中有一个regex:

re.compile('<a\s+href="javascript.*?\(\'(\w+).*?\s.(\d+.+\d+).*?(.*)\'\)\">')

不幸的是,这并不是我想要的,因为编码的单词只会被部分提取,例如,结果是:

^{pr2}$

也许我累了,但我看不出错误在哪里:

hir html:

<td colspan="3" width="100%"><a href="javascript:sendForm('showSubGroups', '160500', 'Fr%C3%BCchte in Alkohol')">Früchte in Alkohol</a></td>
       </tr>
       <tr valign="top">
        <td colspan="3"><img src="NoName_Time_200843_93448%20-Dateien/pix.gif" height="5" width="1"></td>
       </tr>       <tr valign="top">
        <td colspan="3" width="100%"><a href="javascript:sendForm('showSubGroups', '160400', 'Rumtopf')">Rumtopf</a></td>
       </tr>
       <tr valign="top">
        <td colspan="3"><img src="NoName_Time_200843_93448%20-Dateien/pix.gif" height="5" width="1"></td>
       </tr>       <tr valign="top">
        <td colspan="3" width="100%"><a href="javascript:sendForm('showSubGroups', '160300', 'Spirituosen (Bio)')">Spirituosen (Bio)</a></td>
       </tr>
       <tr valign="top">
        <td colspan="3"><img src="NoName_Time_200843_93448%20-Dateien/pix.gif" height="5" width="1"></td>
       </tr>       <tr valign="top">
        <td colspan="3" width="100%"><a href="javascript:sendForm('showSubGroups', '160200', 'Spirituosen zur Verarbeitung in der Confiserie')">Spirituosen zur Verarbeitung in der Confiserie</a></td>
       </tr>
       <tr valign="top">
        <td colspan="3"><img src="NoName_Time_200843_93448%20-Dateien/pix.gif" height="5" width="1"></td>
       </tr>       <tr valign="top">
        <td colspan="3" width="100%"><a href="javascript:sendForm('showSubGroups', '160100', 'Spirituosen, allgemein')">Spirituosen, allgemein</a></td>
       </tr>
       <tr valign="top">
        <td colspan="3"><img src="NoName_Time_200843_93448%20-Dateien/pix.gif" height="5" width="1"></td>
       </tr>                </tbody></table>
            </td>
        </tr>

Tags: srcimgtimetopjavascriptwidthtrtd
2条回答

试试这个:

f = re.compile("sendForm\((?:.*), (.*), (.*)\)")

以文本作为输入,它将给出以下内容:

^{pr2}$

至于解码%C3%BC(用于'u')的话,它似乎只是拉丁语1块中的UTF-8,并额外添加了一些“%”,因为如果将“%”替换为“\x”,它就会解码:

In [39]: '\xC3\xBC'.decode('utf-8')
Out[39]: u'\xfc'

0x00FC是unicode forü。

Beautiful Soup是解析html的一个很好的库。

一旦从html中提取了href,那么使用regex应该很容易。

相关问题 更多 >