2016-12-31 54 views
2

我试图刮掉黄页的数据,但我跑到哪里我无法得到每个企业名称和地址/电话的文本。我正在使用下面的代码,我哪里错了?我试图打印每个企业的文本,但只是打印出来,目的是为了看到它,因为我测试,但一旦我完成后,我会将数据保存到csv。Python 3刮黄页

import csv 
import requests 
from bs4 import BeautifulSoup 

#dont worry about opening this file 
"""with open('cities_louisiana.csv','r') as cities: 
    lines = cities.read().splitlines() 
cities.close()""" 

for city in lines: 
    print(city) 
url = "http://www.yellowpages.com/search? search_terms=businesses&geo_location_terms=amite+LA&page="+str(count) 

for city in lines: 
    for x in range (0, 50): 
     print("http://www.yellowpages.com/search?search_terms=businesses&geo_location_terms=amite+LA&page="+str(x)) 
     page = requests.get("http://www.yellowpages.com/search?search_terms=businesses&geo_location_terms=amite+LA&page="+str(x)) 
     soup = BeautifulSoup(page.text, "html.parser") 
     name = soup.find_all("div", {"class": "v-card"}) 
     for name in name: 
      try: 
       print(name.contents[0]).find_all(class_="business-name").text 
       #print(name.contents[1].text) 
      except: 
       pass 
+0

请勿使用'except:pass',因为您可能有错误而您不知道它。至少使用'except Exception as e:print(e)' – furas

+0

你是对的,因为我的代码确实有错误,我抛出了这个try,除了绕过它。 –

+0

@alecxe抱歉。我刚刚取消了它,我即将进行测试。 :) –

回答

4

你应该遍历搜索结果,那么,对于每一个搜索结果找到的公司名称(用“企业名称”类元素)和地址(用“ADR”类的元素):

for result in soup.select(".search-results .result"): 
    name = result.select_one(".business-name").get_text(strip=True, separator=" ") 
    address = result.select_one(".adr").get_text(strip=True, separator=" ") 

    print(name, address) 

.select().select_one()都得心应手CSS selector methods

+0

令人惊叹。你用这种知识再次拯救了我,它完美地工作。我很高兴了解到获取数据的不同方式。谢谢你的帮助! –

+0

如何添加电话? –

+1

@Kamikaze_goldfish同样的想法应该工作,用'.phone' CSS选择器找到元素。请注意,你可能应该考虑一些没有电话号码的企业.. – alecxe