我试图抓住http://www.nscb.gov.ph/ggi/database.asp,特别是从选择市/省获得的所有表格。我正在使用python与lxml.html和mechanize。到目前为止,我的刮刀工作正常,但是在提交市政[19]“Peñarrubia,Abra”时我得HTTP Error 500: Internal Server Error
。我怀疑这是由于字符编码。我猜是烯字符(上面带有波浪号的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")
答案 0 :(得分: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保护'name'字段)
item.__dict__['name'] = item.name.decode('utf-8').encode('latin-1')
前
br["strMunicipality2"] = [item.name]
答案 1 :(得分:1)
好的,找到了。这是美味的汤,转换为unicode和美化默认返回utf-8。 你应该使用:
response.set_data(soup.prettify(encoding='latin-1'))