我用 python 编写了一个脚本来从某些元素中获取电话号码和地址。问题是我试图解析电话号码的方式绝对是困惑的。我可以为地址做同样的事情。但是,是否有更清洁或更好的方法?
嵌入数据的元素:
html_content='''
<div style="">
<strong>Pamela Banchy, Chief Information Officer</strong>
<br>Western Reserve Hospital<br>
<br>Lyndhurst, OH <br>
<a href="mailto:pbanchy@westernreservehospital.org">pbanchy@westernreservehospital.org</a>
<br>(330) 971-7456<br>
</div>
'''
我用来解析电话号码的表达式和脚本:
from lxml.html import fromstring
tree = fromstring(html_content)
phone = ' '.join([elem.text_content().strip().split()[-2] for elem in tree.cssselect("div")])
phone1 = ' '.join([elem.text_content().strip().split()[-1] for elem in tree.cssselect("div")])
print(phone+phone1)
结果:
(330)971-7456
顺便说一句,地址是 Lyndhurst, OH,电话号码是 (330)971-7456,我已经乱七八糟地抓到了。
请您参考如下方法:
另一种方法:
text_nodes = [node for node in tree.cssselect('div')[0].itertext() if node.split()]
adress, phone = text_nodes[2], text_nodes[4]
