Heim  >  Fragen und Antworten  >  Hauptteil

正则表达式 - Python 中如何用正则匹配中文词组

情景如下,网页中有一段:

<tr>
    <td class="whitetext">此书刊没有复本</td>
</tr>
<tr>
     <td bgcolor="#FFFFFF" class="whitetext"><font color="red"> 此书刊可能正在订购中或者处理中 </font></td>
</tr>

用 BeautifulSoup4 和 Requests 抓取一段网页内容,如果匹配到有“没有复本” 字样,就抛出异常。

如何实现用正则匹配特定的中文词组呢?
(PS 问:如何在 BeautifulSoup4 中搜索特定的文本内容?不限中文 ~ )

高洛峰高洛峰2743 Tage vor983

Antworte allen(1)Ich werde antworten

  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:29:02

    代码

    #! /usr/bin/env python
    # -*- coding: utf-8 -*-
    
    content = """
    <tr>
        <td class="whitetext">此书刊没有复本</td>
    </tr>
    <tr>
         <td bgcolor="#FFFFFF" class="whitetext"><font color="red"> 此书刊可能正在订购中或者处理中 </font></td>
    </tr
    """
    from bs4 import BeautifulSoup
    import re
    tag_soup = BeautifulSoup(content)
    tag_content = tag_soup.get_text().encode("utf-8")
    print re.search(r"没有复本", tag_content)
    

    get_text()从标签中获取所有文字内容,不过是unicode编码,将其用utf-8编码之后,就可以直接用正则表达式搜索。

    Antwort
    0
  • StornierenAntwort