Python:在BeautifulSoup文本中匹配正则表达式

时间:2018-02-07 15:38:34

标签: python regex beautifulsoup

我正在尝试抓取浏览器代码中包含ng-template脚本的网页(对于Angular,我认为):

<script type="text/ng-template" id="modals/location-address.html">
    <div
      class= "modal-address"
      style="background-image: url('https://cdn.ratemds.com/media/locations/location/map/605300-map_kTGdM7j.png');"
    >
      <div class="modal-body">

          <address>

              <strong>Sunshine Perinatology</strong><br>



              7421 Conroy Windermere Road<br>

                null<br>



            Orlando,
            FL,
            United States<br>


              32835

          </address>

      </div>

      <div class="modal-footer">
        <a class="btn btn-default" ng-click="close()">Close</a>

          <a
            href="https://maps.google.com?q=sunshine%20perinatology%2C%207421%20conroy%20windermere%20road%2C%20orlando%2C%20florida%2C%20united%20states%2C%2032835"
            class="btn btn-success"
            target="_blank"
          >
            Get Directions
          </a>

      </div>
    </div>
  </script> 

这是浏览器检查器的示例代码。我到目前为止所做的是使用Selenium来获取页面,然后使用BeautifulSoup来抓取标签。对于这个特定的例子,我的代码看起来如下(没有selenium的代码部分):

import html.parser
import re

h = html.parser.HTMLParser()

select = soup.find("script", id="modals/location-address.html")
items = []
for item in select.contents:
    items.append(str(item).strip())

newContents = '<select>' + ''.join(items).replace('--','')
newSelectSoup = bs.BeautifulSoup(h.unescape(newContents), 'lxml')

pattern = "([A-Z0-9])\w+"
re.findall(pattern, newSelectSoup.find('address').text)

所以,到目前为止,我的方法是使用一些黑客攻击和试用错误来抓取<address>标记内的内容。之后,我正在考虑使用正则表达式来提取文本所需的部分:

Sunshine Perinatology, 7421 Conroy Windermere, Orlando, FL, United States, 32835

但是,执行re.findall(pattern, newSelectSoup.find('address').text)时,结果如下所示:

['S', 'P', '7', 'C', 'W', 'R', 'O', 'F', 'U', 'S', '3']

所以我只得到单词的第一个字母/数字,我不知道为什么。有没有办法通过这种方法获得所有字符串?由于我对正则表达式完全不熟悉,所以我在regexr.com上尝试使用汤输出模式,它完全匹配所有单词。

修改

由于我没有找到从上面的浏览器代码中抓取<address>内容的解决方案,我做了一个中间步骤,用HTMLParser创建一个新的汤。因此,当我使用新的汤代码抓取地址标记时,newSelectSoup.find('address').text的输出如下:

'\nSunshine Perinatology\n \n\n \n 7421 Conroy Windermere Road\n \n null\n \n \n\n Orlando,\n FL,\n United States\n\n \n 32835\n \n '

我的目标是在这个汤输出上使用正则表达式来提取上面的输出,该输出不捕获所有换行符和<{p>}之间的值{/ 1}}

1 个答案:

答案 0 :(得分:1)

您的方法存在的问题是re.findall()只会为捕获的组生成结果,而[A-Z0-9]在您的情况下没有量词。

<小时/> 如果您想要地址,可以使用

import re

string = """
'
Sunshine Perinatology



              7421 Conroy Windermere Road

                null



            Orlando,
            FL,
            United States


              32835

          '
"""

rx = re.compile(r'[A-Z0-9]\w+,?')

address = " ".join([m.group(0) for m in rx.finditer(string)])
print(address)

哪个收益

Sunshine Perinatology 7421 Conroy Windermere Road Orlando, FL, United States 32835