BeautifulSoup4 を使用してこの Web ページをスクレイピングしていますが、BeautifulSoup が返す奇妙な Unicode テキストを取得しています。
これが私のコードです:
site = "http://en.wikipedia.org/wiki/"+a+"_"+str(b)
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(site,headers=hdr)
req.add_header('Accept-enconding', 'gzip') #Header to check for gzip
page = urllib2.urlopen(req)
if page.info().get('Content-Encoding') == 'gzip': #IF checks gzip
data = page.read()
data = StringIO.StringIO(data)
gzipper = gzip.GzipFile(fileobj=data)
html = gzipper.read()
soup = BeautifulSoup(html, fromEncoding='gbk')
else:
soup = BeautifulSoup(page)
section = soup.find('span', id='Events').parent
events = section.find_next('ul').find_all('li')
print soup.originalEncoding
for x in events:
print x
基本的に、x は平易な英語にしたいのです。代わりに、次のようなものが得られます。
<li><a href="/wiki/153_BC" title="153 BC">153 BC</a> – <a href="/wiki/Roman_consul" title="Roman consul">Roman consuls</a> begin their year in office.</li>
この特定の文字列には 1 つの例しかありませんが、そのアイデアは理解できます。
関連: この文字列をいくつかの正規表現やその他の文字列の切り取り方法で切り取ります。切り取りの前または後に、これをプレーン テキストに切り替える必要がありますか? 私はそれが問題ではないと仮定していますが、私はとにかくSOを延期しているので、私は尋ねると思いました.
誰かがこれを修正する方法を知っていれば、私はそれを感謝します。ありがとう
編集:ヒントをくれたJFに感謝します。forループの後にこれを使用しました:
for x in events:
x = x.encode('ascii')
x = str(x)
#Find Content
regex2 = re.compile(">[^>]*<")
textList = re.findall(regex2, x)
text = "".join(textList)
text = text.replace(">", "")
text = text.replace("<", "")
contents.append(text)
しかし、私はまだこのようなものを得ます:
2013 – At least 60 people are killed and 200 injured in a stampede after celebrations at Félix Houphouët-Boigny Stadium in Abidjan, Ivory Coast.
編集: Excel スプレッドシート (csv) を作成してリストに送信する方法は次のとおりです。
rows = zip(days, contents)
with open("events.csv", "wb") as f:
writer = csv.writer(f)
for row in rows:
writer.writerow(row)
そのため、csv ファイルはプログラム中に作成され、リストが生成された後にすべてがインポートされます。その時点で読みやすいテキストにする必要があるだけです。