6

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")
4

2 に答える 2

1

わかりました、それを見つけました。これは、Unicodeに変換され、デフォルトでutf-8を返す美しいスープです。次を使用する必要があります。

response.set_data(soup.prettify(encoding='latin-1'))
于 2011-07-18T12:48:12.517 に答える
1

手早く汚いハック:

def _pairs(self):
    return [(k, v.decode('utf-8').encode('latin-1')) for (i, k, v, c_i) in self._pairs_and_controls()]

from mechanize import HTMLForm
HTMLForm._pairs = _pairs

または侵襲性の低いもの(クラス Item が「名前」フィールドを保護するため、他の解決策はないと思います)

item.__dict__['name'] = item.name.decode('utf-8').encode('latin-1')

br["strMunicipality2"] = [item.name]
于 2011-07-15T00:09:59.380 に答える