从这个网站上抓取地址和电话号码

如何使用bs4和 pandas 库从和联系信息类中抓取数据并导出到 csv 文件?从这个网站?我需要有关如何从标签和联系信息类中抓取数据的帮助。


import pandas as pd

import bs4

import requests

import re

full_dict={'Title':[],'Description':[],'Address':[]}

res=requests.get("https://cupcakemaps.com/cupcakes/cupcakes-near-me/p:2")   

listings=soup.findAll(class_='media')

for listing in listings:

    listing_title=listing.find(True,{'title':True}).attrs['title']

    listing_Description=listing.find('p',{'class':'summary-desc'})

    listing_address=listing.find('p',{'class':'contact-`info'}).text=re.compile(r'[0-9]{0,4}')`


月关宝盒
浏览 89回答 1
1回答

幕布斯7119047

.strip()- Python 的内置函数用于从字符串中删除所有前导和尾随空格。.to_csv()- 将对象写入逗号分隔值 (csv) 文件。前任。import pandas as pdfrom bs4 import BeautifulSoup,Tagimport requestsimport reres=requests.get("https://cupcakemaps.com/cupcakes/cupcakes-near-me/p:2")soup = BeautifulSoup(res.text,'lxml')listings=soup.findAll(class_='media')data = []for listing in listings:    listing_title=listing.find(True,{'title':True}).attrs['title']    listing_Description=listing.find('p',{'class':'summary-desc'})    if isinstance(listing_Description,Tag):        listing_Description = listing_Description.text.strip()    listing_address=listing.find('p',{'class':'contact-info'})    if isinstance(listing_address,Tag):        number_text = listing_address.text.strip()        listing_address = ''.join(filter(str.isdigit,number_text))    full_dict = {'Title': listing_title, 'Description': listing_Description, 'Address': listing_address}    data.append(full_dict)df = pd.DataFrame(data)# saved data into csv filedf.to_csv("contact.csv")print(df)输出/输出:                                               Title                                        Description     Address0  Explore Category 'Anaheim CA Birthday Cupcakes...  Delectable Anaheim, CA - Delectable check out ...  71471560861  Explore Category 'Costa Mesa CA Birthday Cupca...  Lisa's Gourmet Snacks Costa Mesa CA  check out...  71442758142  Explore Category 'Shorewood IL Birthday Cupcak...  Acapulco Bakery Inc Shorewood, IL - Acapulco B...  81572917373  Explore Category 'San Francisco CA Birthday Cu...  Hilda's Mart & Bake Shop San Francisco CA  che...  41533331224  Explore Category 'Los Angeles CA Birthday Cupc...  Lenny's Deli Los Angeles, CA - Lenny's Deli ch...  31047557715  Explore Category 'San Francisco CA Birthday Cu...  Sweet Inspirations San Francisco CA  check out...        None6  Explore Category 'Costa Mesa CA Birthday Cupca...  The Cupcake Costa Mesa CA  check out  The Cupc...  94964205717  Explore Category 'Los Angeles CA Birthday Cupc...  United Bread & Pastry Inc Los Angeles CA  chec...  32366100378  Explore Category 'Garden Grove CA Birthday Cup...  Pescadores Garden Grove CA  check out  Pescado...  71453955859  Explore Category 'Bakersfield CA Birthday Cupc...  Bimbo Bakeries Usa Bakersfield CA  check out  ...  6613219352
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python