【发布时间】:2017-10-15 06:29:35
【问题描述】:
我试图抓取商店位置的文本详细信息,并使用 BeautifulSoup 将它们写入 csv。阿拉巴马州的 2 家商店属于 LocationSecContent 类,亚利桑那州的 17 家商店属于另一类 LocationSecContent。 在乔治亚州,1st store Airport 位于 LocationSecContent 类中的一个名为 location 的类中,而乔治亚州的其余 4 个位于 LocationSecContent 中的另一个类位置中。 我想抓取文本详细信息并将商店详细信息(如名称、位置、街道、电话、传真、营业时间内容和所有详细信息)写入 csv 文件。我在firefox中使用firebug。对不起,如果有任何错误,我是beautifulsoup的初学者。
这是我尝试过的:
from bs4 import BeautifulSoup
import requests
page = requests.get('http://freshvites.com/store-locator/')
soup = BeautifulSoup(page.text, 'html.parser')
d={}
for table in soup.find_all("div", {"class":"content freshvites-location"}):
table
for col in table.find_all("td"):
LocationSecHdr=col.find_all("div",{'class':'LocationSecHdr'})
Location=col.find_all("div",{'class':'location'})
dt="LocationSecHdr:%s,Location: %s" %(LocationSecHdr, Location)
zx=BeautifulSoup(dt, "html.parser")
print zx.get_text()
我无法遍历行并抓取文本。
方法二:
from bs4 import BeautifulSoup
import requests
page = requests.get('http://freshvites.com/store-locator/')
#print page
soup = BeautifulSoup(page.text, 'html.parser')
#print soup.find_all('a')
for table in soup.find_all("div",{'class':'content freshvites-location'}):
table
LocationSecHdr=''
LocationSecContent=''
Location=''
LocationTitle=''
Phone=''
Fax=''
HoursTitle=''
HoursContent=''
for col in table.find_all("td"):
LocationSecHdr=col.find_all("div",{'class':'LocationSecHdr'})
#LocationSecContent= col.find_all("div",{'class':'LocactionSecContent'})
#Location= col.find_all("div",{'class':'location'})
LocationTitle= col.find_all("div",{'class':'locationTitle'})
Phone= col.find_all("div",{'class':'Phone'})
Fax= col.find_all("div",{'class':'Fax'})
HoursContent=col.find_all("div",{'class':'HoursContent'})
data="LocationSecHdr: %s, LocationSecContent: %s, Location:%s, LocationTitle : %s, Phone:%s, Fax :%s, HoursContent:%s " %(LocationSecHdr, LocationSecContent, Location, LocationTitle, Phone, Fax, HoursContent)
zax=BeautifulSoup(data,"html.parser")
print zax.get_text()
如果我尝试这段代码,我无法获得商店的地址,我也不知道如何将这些详细信息作为字典获取
【问题讨论】:
-
你尝试过的东西有什么问题?
-
循环没有得到迭代
-
哪个循环?你怎么知道的?
-
我在这个循环中遇到关键错误或列表索引超出范围 LocationSecHdr=col[0].find(text=True)
-
我在您正在抓取的网站上找不到包含位置的表格。在我看来,您实际上是在寻找
<div class="location">- 如果没有,您能否提供一些示例数据?
标签: python csv web-scraping beautifulsoup