我正在尝试使用BeautifulSoup从网页中解析数据。到目前为止,我已经使用以下代码从表格中获取了所需的数据:
def webParsing(canvas):
url='http://www.cmu.edu/dining/hours/index.html'
try:
page= urllib.urlopen(url)
except:
print 'Error while opening html file. Please ensure that you',
print ' have a working internet connection.'
return
sourceCode=page.read()
soup=BeautifulSoup(sourceCode)
#heading=soup.html.body.div
tableData=soup.table.tbody
parseTable(canvas,tableData)
def parseTable(canvas,tableData):
canvas.data.hoursOfOperation=dict()
rowTag='tr'
colTag='td'
for row in tableData.find_all(rowTag):
row_text=[]
for item in row.find_all(colTag):
text=item.text.strip()
row_text.append(text)
(locations,hoursOpen)=(row_text[0],row_text[1])
locations=locations.split(',')
for location in locations:
canvas.data.hoursOfOperation[location]=hoursOpen
print canvas.data.hoursOfOperation
如您所见,第一列中的“items”与第二列中的“items”通过字典进行映射。当打印数据时,数据基本上是我想要的,但在Python中,这些字符串中有很多格式,例如“\n”或“\xe9”或“\n\xao”。有没有办法删除所有格式?换句话说,删除所有换行符,表示特定编码的任何内容,表示重音字符的任何内容,只获取字符串文字?我不需要最有效或最安全的方法,我是初学者,因此最好使用最简单的方法!谢谢!