http://www.nscb.gov.ph/ggi/database.asp、具体的には自治体/州を選択して取得したすべてのテーブルをスクレイピングしようとしています。私はlxml.htmlとmechanizeでpythonを使用しています。私のスクレーパーは今のところ問題なく動作しますHTTP Error 500: Internal Server Error
が、自治体[19]「アブラのペニャルビア」を提出すると取得します。これは文字エンコーディングが原因であると思われます。私の推測では、en 文字 (上にチルダが付いた n) がこの問題を引き起こしていると思われます。どうすればこれを修正できますか?
私のスクリプトのこの部分の実際の例を以下に示します。私はPythonを使い始めたばかりなので(そして、SOで見つけたスニペットをよく使用します)、さらにコメントをいただければ幸いです。
from BeautifulSoup import BeautifulSoup
import mechanize
import lxml.html
import csv
class PrettifyHandler(mechanize.BaseHandler):
def http_response(self, request, response):
if not hasattr(response, "seek"):
response = mechanize.response_seek_wrapper(response)
# only use BeautifulSoup if response is html
if response.info().dict.has_key('content-type') and ('html' in response.info().dict['content-type']):
soup = BeautifulSoup(response.get_data())
response.set_data(soup.prettify())
return response
site = "http://www.nscb.gov.ph/ggi/database.asp"
output_mun = csv.writer(open(r'output-municipalities.csv','wb'))
output_prov = csv.writer(open(r'output-provinces.csv','wb'))
br = mechanize.Browser()
br.add_handler(PrettifyHandler())
# gets municipality stats
response = br.open(site)
br.select_form(name="form2")
muns = br.find_control("strMunicipality2", type="select").items
# municipality #19 is not working, those before do
for pos, item in enumerate(muns[19:]):
br.select_form(name="form2")
br["strMunicipality2"] = [item.name]
print pos, item.name
response = br.submit(id="button2", type="submit")
html = response.read()
root = lxml.html.fromstring(html)
table = root.xpath('//table')[1]
data = [
[td.text_content().strip() for td in row.findall("td")]
for row in table.findall("tr")
]
print data, "\n"
for row in data[2:]:
if row:
row.append(item.name)
output_mun.writerow([s.encode('utf8') if type(s) is unicode else s for s in row])
response = br.open(site) #go back button not working
# provinces follow here
どうもありがとうございました!
編集:具体的には、この行でエラーが発生します
response = br.submit(id="button2", type="submit")