【发布时间】:2018-07-17 23:21:43
【问题描述】:
我正在尝试抓取在浏览器代码中包含 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 '
我的目标是在这个汤输出上使用正则表达式来提取上面没有捕获所有换行符的输出和两者之间的 null 值
【问题讨论】:
标签: python regex beautifulsoup