我正在努力搜集公司的联系信息,除了电话号码以外,我还能得到其他所有的信息。这是html
<ul>
<li>
<h3>Harrrrrell INC</h3>
</li>
<li>43 Airpark Ct</li>
<li>Alabaster, MD 35107</li>
<li><span style="font-weight: bold;">Phone</span>: 888-232-8358</li>
<li><span style="font-weight: bold;">Corporate URL</span>: <a href="http://www.hhsales.com" rel="nofollow" target="new">www.h23hsales.com</a></li>
<li><span style="font-weight: bold;">More Detail</span>:<br> <a href="https://www.collierreporting.com/company/harrell-and-hall-enterprises-inc-alabaster-al">Click for Full Harrell & Hall Enterprises INC Dossier</a></li>
</ul>
这个python脚本适用于这个html中除电话号码之外的所有其他内容。你知道吗
for companyLIST in result[0:]:
try:
companyname = companyLIST.find('h3').contents[0]
print("Company Name ",str(companyname) )
except Exception as e:
print("errror",str(e))
try:
companySt = companyLIST.find_all('li')[1].contents[0]
print("Company St ",str(companySt) )
except Exception as e:
print("errror",str(e))
try:
companyCity = companyLIST.find_all('li')[2].contents[0]
print("Company City ",str(companyCity) )
except Exception as e:
print("errror",str(e))
try:
companyPhone= companyLIST.find('li')[3].contents[0]
print("Company Phone ",companyPhone )
except Exception as e:
print("errror",str(e))
try:
companyWeb = companyLIST.find('a')['href']
print("Company Web ",str(companyWeb) )
print(" " )
except Exception as e:
print("errror",str(e))
这是的示例输出
公司名称Harrrrell公司
公司St 43 Airpark Ct
马里兰州阿拉巴斯特市公司,邮编:35107
错误3
公司网站https://www.collierreporting.com/company/harrell-and-hall-enterprises-inc-alabaster-al
Traceback (most recent call last):
File "sample.py", line 26, in <module> companyPhone = soup.find('li')[3].contents[0] File "...dist-packages/bs4/element.py", line 1011, in __getitem__ return self.attrs[key] KeyError: 3
如何重写下面的代码来获得电话号码?你知道吗
companyPhone= companyLIST.find('li')[3].contents[0]
print("Company Phone ",companyPhone )
替换
与
上面的代码按“:”字符分隔列表,选择最后一个元素,并删除无用的信息。最后我们只有电话号码作为一个单独的字符串。您可以对其余的行执行相同的操作,只需明智地选择拆分字符/字符串,并使用replace函数清除结果列表元素。你知道吗
希望有用。你知道吗
我猜您正在使用beatifulsoup4库解析HTML。如果是,您可以从html获取电话号码,如下所示:
相关问题 更多 >
编程相关推荐