网站抓取使用Beautifulsoup 4 -提取联系人信息



HTML代码截图

这是我的第一个帖子,如果我打破了一些规则,请原谅我。我试图使用看起来像 的代码web抓取供应商信息
soup.find_all('span', class_ = "class-name")

请参考附件图片。我想得到联系电话,但它不是作为文本或类似的东西给出的。每个数字似乎都在它自己的类标签中,甚至在里面这个数字不在文本中。我也不熟悉webdev,所以如果有人能给建议,我真的很感激。

url: https://www.justdial.com/Pune/Sunrise-Enterprises-Budhwar-Peth/020PXX20-XX20-130817131104-Z3I2_BZDET?xid=UHVuZSBFbGVjdHJvbmljIENvbXBvbmVudCBEZWFsZXJz

另一个有多个联系方式的类似页面是:https://www.justdial.com/Pune/Galaxy-Enterprises-And-Electronics-Behind-Bharti-Vidyapeeth-Near-Ichapurti-Mandir-Ambegaon-Budruk/020PXX20-XX20-140930130951-K4X6_BZDET?xid=UHVuZSBFbGVjdHJvbmljIENvbXBvbmVudCBEZWFsZXJz

感谢

第二个样式标签包含css代码,其中icon-xx属性的序列定义了该属性与哪个数字匹配。这用于在网页上加载带有此数字的图像,因此没有数字要抓取。解决方案是1)将icon-xx属性映射到基于它们在css字符串中的序列的数字;2)在HTML正文中查找电话号码跨度并检索匹配的数字:

import requests
from bs4 import BeautifulSoup
url = 'https://www.justdial.com/Pune/Sunrise-Enterprises-Budhwar-Peth/020PXX20-XX20-130817131104-Z3I2_BZDET?xid=UHVuZSBFbGVjdHJvbmljIENvbXBvbmVudCBEZWFsZXJz'
r = requests.get(url, headers={'User-Agent' : "Mozilla/5.0 (Windows NT 6.1; Win64; x64)"})
soup = BeautifulSoup(r.text, "html.parser")
text = soup.find_all('style', {"type": "text/css"}, text=True)[1]
data = text.contents[0].split('smoothing:grayscale}', 1)[1].split('n')[0]
icon_items = [i.split(':')[0] for i in data.split('.') if len(i)>0]
items = ['0','1','2','3','4','5','6','7','8','9','+','-',')','(']
full_list = dict(zip(icon_items, items))
phone_numbers = soup.find_all('span',{'class':'telnowpr'})
for i in phone_numbers:
numbers = i.find_all('span')
number = [full_list[y.attrs['class'][1]] for y in numbers]
print("phone number: " + ''.join([str(elem) for elem in number]) )

结果:

phone number: 07947197693
phone number: 07947197693
phone number: 07947197693

最新更新