无法从某些html元素中提取某些地址

2024-10-02 20:31:07 发布

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

我用python编写了一个脚本,从html元素块中提取地址。地址在两个br标记内。然而,当我运行我的脚本时,我得到这个[<br/>, <br/>, <br/>, <br/>]作为输出

我怎样才能得到完整的地址

我试图从中收集地址的html元素:

<div class="ACA_TabRow ACA_FLeft">
 Mailing
 <br/>
 1961 MAIN ST #186
 <br/>
 WATSONVILLE, CA, 95076
 <br/>
 United States
 <br/>
</div>

我已经试过了:

from bs4 import BeautifulSoup
import re

html = """
<div class="ACA_TabRow ACA_FLeft">
 Mailing
 <br/>
 1961 MAIN ST #186
 <br/>
 WATSONVILLE, CA, 95076
 <br/>
 United States
 <br/>
</div>
"""
soup = BeautifulSoup(html,"lxml")
items = soup.find(class_="ACA_TabRow").find(string=re.compile("Mailing")).find_next_siblings()
print(items)

Tags: brdiv脚本元素main地址htmlfind
3条回答
from bs4 import BeautifulSoup
import re

html = """
<div class="ACA_TabRow ACA_FLeft">
 Mailing
 <br/>
 1961 MAIN ST #186
 <br/>
 WATSONVILLE, CA, 95076
 <br/>
 United States
 <br/>
</div>
"""
soup = BeautifulSoup(html,"lxml")
items = soup.find(class_="ACA_TabRow")

items_list = items.text.split('\n')

results = [ x.strip() for x in items_list if x.strip() != '' ]

输出:

print (results)
['Mailing', '1961 MAIN ST #186', 'WATSONVILLE, CA, 95076', 'United States']

我将继续检查div startswith Mailing中的stripped字符串

soup = BeautifulSoup(html,"lxml")
items = soup.find(class_="ACA_TabRow")

for i,item in enumerate(items.stripped_strings):
    if i==0 and not item.startswith('Mailing'):
        break
    if i!=0:
        print(item)

输出

1961 MAIN ST #186
WATSONVILLE, CA, 95076
United States

看来我找到了更好的解决办法:

from bs4 import BeautifulSoup
import re

html = """
<div class="ACA_TabRow ACA_FLeft">
 Mailing
 <br/>
 1961 MAIN ST #186
 <br/>
 WATSONVILLE, CA, 95076
 <br/>
 United States
 <br/>
</div>
"""
soup = BeautifulSoup(html,"lxml")
items = soup.find(class_="ACA_TabRow").find(string=re.compile("Mailing")).find_parent()
find_text = ' '.join([item.strip() for item in items.strings])
print(find_text)

输出:

Mailing 1961 MAIN ST #186 WATSONVILLE, CA, 95076 United States

相关问题 更多 >