Python:在beautifulsouptex中匹配regex

2024-10-02 08:30:59 发布

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

我正在尝试对浏览器代码中包含ng模板脚本(我认为是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>标记中对内容进行爬网。之后,我考虑使用regex来提取文本中需要的部分,即:

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']

所以我只知道单词的第一个字母/数字,我不知道为什么。有没有办法用这种方法得到所有的字符串?因为我对regex完全不熟悉,所以我尝试了使用soup输出的模式regexr.com,与所有单词完全匹配。你知道吗

编辑

因为我没有找到从上面的浏览器代码抓取<address>内容的解决方案,所以我做了中间步骤,用HTMLParser创建了一个新的soup。因此,当我用新的soup代码爬行地址标记时,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 '

我的目标是在这个soup输出上使用regex来提取上面的输出,该输出没有捕获所有的换行符和中间的null


Tags: 代码textbrdivaddresshtmlscript浏览器
1条回答
网友
1楼 · 发布于 2024-10-02 08:30:59

你的方法的问题是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

相关问题 更多 >

    热门问题