【发布时间】:2018-12-28 07:37:28
【问题描述】:
这是我第一次使用BeautifulSoup,我正试图从当地便利店中删除商店位置数据。
但是,当数据被传递到 CSV 文件时,我在尝试删除空行时遇到了一些问题,我试过 .replace('\n','') 和 .strip() 都没有工作。
此外,我在拆分被抓取并包含在同一个兄弟方法中的数据时遇到问题。
我在下面添加了脚本:
from bs4 import BeautifulSoup
from requests import get
import urllib.request
import sched, time
import csv
url = 'http://www.cheers.com.sg/web/store_location.jsp'
response = get(url)
soup = BeautifulSoup(response.text, 'html.parser')
#print (soup.prettify())
#open a file for writing
location_data = open('data/soupdata.csv', 'w', newline='')
#create the csv writer object
csvwriter = csv.writer(location_data)
cheers = soup.find('div' , id="store_container")
count = 0
#Loop for Header tags
for paragraph in cheers.find_all('b'):
header1 = paragraph.text.replace(':' , '')
header2 = paragraph.find_next('b').text.replace(':' , '')
header3 = paragraph.find_next_siblings('b')[1].text.replace(':' , '')
if count == 0:
csvwriter.writerow([header1, header2, header3])
count += 1
break
for paragraph in cheers.find_all('br'):
brnext = paragraph.next_sibling.strip()
brnext1 = paragraph.next_sibling
test1 = brnext1.next_sibling.next_sibling
print(test1)
csvwriter.writerow([brnext, test1])
location_data.close()
生成的输出示例:
输出应该是什么样子的示例:
我怎样才能做到这一点?
提前致谢。
【问题讨论】:
标签: python csv web-scraping beautifulsoup